在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
,然后根据首次调用的结果选择要解析的其他解析器args.诀窍是首先使用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屋!