Python:带有 Main 命令和 Sub 命令的 ArgParse

标签 python argparse

嗨,我正在使用 ArgParse 来处理我的参数。我希望代码像这样工作

# Main function
$ myApp -i INPUT -o OUTPUT -s STUFF 
<小时/>
# Configure function
$ myApp config -a conf1 -b conf2  
<小时/>
import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter) 
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)
args = parser.parse_args()

subp = parser.add_subparsers()
conf_parser = subp.add_parser('config', help='configure')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
conf_args = conf_arser.parse_args()

这是输出

python sandbox/test1.py  --help
usage: test1.py [-h] -i I -o O [-s S]

myApp

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff

我没有显示配置参数。我不确定我在这里做错了什么。

谢谢!

最佳答案

解决了

<小时/>
import argparse
from argparse import RawTextHelpFormatter

parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)

subp = parser.add_subparsers(help='configure')
conf_parser = subp.add_parser('config')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
args = parser.parse_args()
<小时/>
python sandbox/test1.py --help
usage: test1.py [-h] -i I -o O [-s S] {config} ...

myApp

positional arguments:
  {config}    configure

optional arguments:
  -h, --help  show this help message and exit
  -i I        input
  -o O        output
  -s S        stuff
<小时/>
python sandbox/test1.py config --help
usage: test1.py config [-h] [-a A] [-b B]

optional arguments:
  -h, --help  show this help message and exit
  -a A        a config file
  -b B        b config file

关于Python:带有 Main 命令和 Sub 命令的 ArgParse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44346432/

相关文章:

python - 没有破折号但带有附加参数的可选 python 参数?

python - python Argparse 中的额外字符?

python - 为什么将多处理与实例方法与函数一起使用时会得到不同的结果?

python - 在 Python Matplotlib 中向现有绘图添加多边形层

python - django 将枚举中的项目翻译成其他语言

python - 通过元组中的名称访问变量

python - python argparse中的多行帮助显示

python - 使用卷积自动编码器从 2D 到 3D

python - 在没有任何参数的情况下调用脚本时使用 Python argparse 显示帮助消息

python - 如何使用 'argparse' 指定两个必需参数(包括子命令)?