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?
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With