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

时间:2017-06-03 16:58:25

标签: 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

我没有得到配置args显示。我不确定我在这里做错了什么。

谢谢!

1 个答案:

答案 0 :(得分:3)

解决了它

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