本文介绍了argparse接受一切的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种方法使argparse.ArgumentParser
不会在读取未知选项时引发异常,而是将所有带有值的未知选项放在字典中,而将没有值的那些放在列表中?
Is there a way to have an argparse.ArgumentParser
not raise an exception upon reading an unknown option, but rather put all the unknown options with values in a dictionary, and those without a value in a list?
例如,假设在解析器中没有为prog.py
定义任何参数,而我传递了两个参数:
For example, say no arguments were defined in the parser for prog.py
, and I pass two arguments:
./prog.py --foo bar --baz
我想要以下内容:
parsed = parser.parse_args()
vals = parsed.unknown_with_vals
novals = parsed.unknown_without_vals
print(vals)
#{'foo' : 'bar'}
print(novals)
#['baz']
可以做到吗?
推荐答案
known, unknown_args = parser.parse_known_args(...)
正如@ben w在评论中指出的那样,您如何解析unknown_args
取决于您,例如,采用以下语法:
As @ben w noted in the comment how do you parse unknown_args
is upto you e.g., with the following grammar:
unknown_args = *(with_val / without_val) EOS
with_val = OPT 1*VALUE
without_val = OPT
OPT = <argument that starts with "--">
VALUE = <argument that doesn't start with "--">
或作为正则表达式:
(O V+ | O)* $
注意:在这种情况下,禁止使用孤立值.
Note: orphan values are forbidden in this case.
d = {}
for arg in unknown_args:
if arg.startswith('--'): # O
opt = arg
d[opt] = []
else: # V
d[opt].append(arg) #NOTE: produces NameError if an orphan encountered
with_vals = {k: v for k, v in d.items() if v}
without_vals = [k for k, v in d.items() if not v]
这篇关于argparse接受一切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!