argparse accept everything

回眸只為那壹抹淺笑 提交于 2019-12-08 15:02:38

问题


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?

For example, say no arguments were defined in the parser for prog.py, and I pass two arguments:

./prog.py --foo bar --baz

I would like the following:

parsed = parser.parse_args()
vals = parsed.unknown_with_vals
novals = parsed.unknown_without_vals

print(vals)
#{'foo' : 'bar'}
print(novals)
#['baz']

Can this be done?


回答1:


known, unknown_args = parser.parse_known_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 "--">

Or as a regex:

(O V+ | O)* $

Note: orphan values are forbidden in this case.

Example

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]


来源:https://stackoverflow.com/questions/9643248/argparse-accept-everything

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!