这显然是的一个尴尬的规范,我怀疑大多数其他POSIX风格的解析器。
扫描sys.argv
并调整解析器定义是一种可能的方法。
另一种是用一个2级剖析,以parse_known_args
:
import argparse
usage = 'prog [-h] [--simulation] [arg1 arg2 arg3 arg4]'
parser1 = argparse.ArgumentParser(usage=usage)
parser1.add_argument('--simulation', action='store_true')
# or omit the `store_true` if it just takes one argument
# other possible optionals
parser2 = argparse.ArgumentParser()
#parser2.add_argument("arg1", type = bool) # not a valid type parameter
parser2.add_argument("arg2")
parser2.add_argument("arg3", type = int)
parser2.add_argument("arg4")
# positionals are required, unless nargs=? or *
args, extras = parser1.parse_known_args()
if not args.simulation:
args = parser2.parse_args(extras, namespace=args)
elif extras:
parser1.error('cannot use --simulation with args')
print(args)
可能的运行包括:
1526:~/mypy$ python stack41556997.py -h
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4]
optional arguments:
-h, --help show this help message and exit
--simulation
1526:~/mypy$ python stack41556997.py --simulation
Namespace(simulation=True)
1527:~/mypy$ python stack41556997.py 1 2 3
Namespace(arg2='1', arg3=2, arg4='3', simulation=False)
1527:~/mypy$ python stack41556997.py 1 2 3 --sim
usage: prog [-h] [--simulation] [arg1 arg2 arg3 arg4]
stack41556997.py: error: cannot use --simulation with args
注意,帮助不包括两套。我在自定义用法中包含了一些信息,但arg#
没有帮助行。生成一个好的help
消息将与您的规格尴尬。
我跳过了你的arg1
。 type=bool
不是有效的type
参数。请参阅我的解释Parsing boolean values with argparse
我将--simulation
更改为store_true
,因为您说它没有任何参数。这是接受True/False的正常方式。
Subparsers通常是接受不同模式参数的最佳工具。在这种情况下,你可以有一个叫做'simulate'的subparser不需要任何参数,另一个叫'somethingelse'需要4个参数。
我打算建议一个与--simulation
和可选项互斥的组。但一个store_true
的论点不适用于这样的组。
=============
子分析器路线:
parser = argparse.ArgumentParser()
sp = parser.add_subparsers(dest='cmd')
sp.add_parser('simulate')
parser2 = sp.add_parser('other')
parser2.add_argument("arg2")
parser2.add_argument("arg3", type = int)
parser2.add_argument("arg4")
print(parser.parse_args())
测试:
1552:~/mypy$ python stack41556997.py -h
usage: stack41556997.py [-h] {simulate,other} ...
positional arguments:
{simulate,other}
optional arguments:
-h, --help show this help message and exit
1557:~/mypy$ python stack41556997.py simulate
Namespace(cmd='simulate')
1557:~/mypy$ python stack41556997.py other -h
usage: stack41556997.py other [-h] arg2 arg3 arg4
positional arguments:
arg2
arg3
arg4
optional arguments:
-h, --help show this help message and exit
1557:~/mypy$ python stack41556997.py other 1 2 3
Namespace(arg2='1', arg3=2, arg4='3', cmd='other')
注意,arg3
type
转换的输入到一个整数。其他人留作字符串。有了这个设置,args.cmd
将成为子分析器的名称,与布尔型args.simulation
属性不完全相同。
==================
甲标记默认参数不要求的。位置参数是必需的,除非nargs
值为'?'要么 '*'。您无法为位置提供“必需”参数。
你使用'type = bool'是有问题的。请参阅我答案中的链接。 – hpaulj