在python中解析参数 [英] parsing argument in python
问题描述
我有一个问题,我正在努力寻找解决方案.我不确定我是否可以用 argparse 做到这一点.
I have a problem I am trying to find a solution. I am not sure if I can do it with argparse.
我希望能够指定一个选项
I want to be able to specify an option
myprog -a 1
myprog -a 2
现在当我有 a = 1 时,我希望能够指定 b 和 c.但是当a = 2时,我只能指定d.
Now when I have a = 1, I want to be able to specify b and c. But when a = 2, I can only specify d.
myprog -a 1 -b 3 -c 0
myprog -a 2 -d 3
还必须始终指定a
推荐答案
您不能将切换值作为单个 parse_args
调用执行此操作,但您可以执行以下操作之一:
You can't do this with switched values as a single parse_args
call, but you can do one of:
- 使用子命令/子解析器莉>
- 在完全配置解析器并在完整命令行上运行之前先做部分解析,首先只检查
a
,然后根据第一次调用的结果选择额外的解析器参数进行解析.诀窍是使用parse_known_args
用于第一次调用,因此它处理a
(它可以识别)并忽略其他所有内容.
- Use sub-commands/sub-parsers
- Do partial parsing before fully configuring the parser and running on the complete command line, at first only checking for
a
, and then selecting the additional parser args to parse based on the result of the first call. The trick is to useparse_known_args
for the first call, so it handlesa
(which it recognizes) and ignores everything else.
例如,对于方法#2,您可以这样做:
For example, for approach #2, you could do:
parser = argparse.ArgumentParser()
parser.add_argument('-a', required=True, type=int, choices=(1, 2)
args = parser.parse_known_args()
if args.a == 1:
parser.add_argument('-b', ...)
parser.add_argument('-c', ...)
args = parser.parse_args()
else:
parser.add_argument('-d', ...)
args = parser.parse_args()
这种方法的缺点是因错误使用而吐出的使用信息将不完整;您必须手动在基本解析器中包含指定真实"用法的文本,这并不有趣.子解析器无法根据值切换进行切换,但它们具有统一、连贯的用法显示.
Downside to this approach is that the usage info spat out for incorrect usage will be incomplete; you'd have to include the text specifying the "real" usage in the base parser manually, which is no fun. Subparsers can't be toggled based on value switches, but they have a unified, coherent usage display.
这篇关于在python中解析参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!