Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse accept everything

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?

like image 781
antony Avatar asked Mar 10 '12 01:03

antony


1 Answers

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]
like image 186
jfs Avatar answered Sep 24 '22 16:09

jfs