对于argparse,这显然是一个尴尬的规范,我怀疑大多数其他 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,因为您说它没有任何参数。这是接受真假的正常方式。
子解析器通常是接受不同参数模式的最佳工具。在这种情况下,您可以有一个不需要任何参数的名为“simulate”的子解析器,以及另一个需要 4 个位置的调用“somethingelse”。
我将建议一个带有 --simulation 和 --other 选项的互斥组。但是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 值为“?”,否则需要位置参数要么 '*'。您不能为位置提供“必需”参数。