Skip to content
Advertisement

Is it possible to use argparse to capture an arbitrary set of optional arguments?

Is it possible to use argparse to capture an arbitrary set of optional arguments?

For example both the following should be accepted as inputs:

python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3

python script.py required_arg1 --varA valueA --var2 value2 --varB valueB

a priori I don’t know what optional arguments would be specified receive but would handle them accordingly.

Advertisement

Answer

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')

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement