This is kind of a hackish way, but it works well:
Check, which arguments are not added and add them
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("foo")
parser.add_argument("-bar", type=int)
# parser can have any arguments, whatever you want!
parsed, unknown = parser.parse_known_args() # this is an 'internal' method
# which returns 'parsed', the same as what parse_args() would return
# and 'unknown', the remainder of that
# the difference to parse_args() is that it does not exit when it finds redundant arguments
for arg in unknown:
if arg.startswith(("-", "--")):
# you can pass any arguments to add_argument
parser.add_argument(arg.split('=')[0], type=<your type>, ...)
args = parser.parse_args()
For example:
python3 arbitrary_parser.py ha -bar 12 -extra1 value1 -extra2 value2
Then the result would be
args = Namespace(bar=12, foo='ha', extra1='value1' extra2='value2')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…