Is it possible to use argparse
to capture an arbitrary set of optional arguments?
For example both the following should be accepted as inputs:
JavaScript
x
4
1
python script.py required_arg1 --var1 value1 --var2 value2 --var3 value3
2
3
python script.py required_arg1 --varA valueA --var2 value2 --varB valueB
4
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
JavaScript
1
18
18
1
import argparse
2
parser = argparse.ArgumentParser()
3
parser.add_argument("foo")
4
parser.add_argument("-bar", type=int)
5
# parser can have any arguments, whatever you want!
6
7
parsed, unknown = parser.parse_known_args() # this is an 'internal' method
8
# which returns 'parsed', the same as what parse_args() would return
9
# and 'unknown', the remainder of that
10
# the difference to parse_args() is that it does not exit when it finds redundant arguments
11
12
for arg in unknown:
13
if arg.startswith(("-", "--")):
14
# you can pass any arguments to add_argument
15
parser.add_argument(arg.split('=')[0], type=<your type>, )
16
17
args = parser.parse_args()
18
For example:
JavaScript
1
2
1
python3 arbitrary_parser.py ha -bar 12 -extra1 value1 -extra2 value2
2
Then the result would be
JavaScript
1
2
1
args = Namespace(bar=12, foo='ha', extra1='value1' extra2='value2')
2