I have this snippet for illustrative purpose that doesn’t work at all.
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--action", nargs="+")
parser.add_argument("--number", nargs="+", default=1)
parser.add_argument("--some-parameter-to-action", nargs="+", required=True)
args = parser.parse_args()
I’m trying to parse an arbitrary number of action
parameters, each action
should have an associated number
and some-parameter-to-action
, potentially with a default value. Passing another action
should create a new one and the following --number
and --some-parameter-to-action
flags should be associated with the action
that preceeded it.
Examples, I want to be able to pass all or a subset of these in a single invocation of the script:
--action say -n 3 --some-parameter-to-action foo
--action bla --some-parameter-to-action no
--action nothing # error
Is something like this possible in python?
4
I agree with the comments. What you have there is complicated and unconventional. Also, the idea of taking the last values as default is a bad idea: it is hard to implement, hard to explain to the end user. Here is my idea of how to implement it, consider the script triplet.py
:
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", "--triplet",
nargs=3,
default=[],
metavar=("ACTION", "NUMBER", "PARAM"),
action="append",
)
options = parser.parse_args()
print(options)
Some interactions:
$ ./triplet.py -h
usage: triplet.py [-h] [-t ACTION NUMBER PARAM]
options:
-h, --help show this help message and exit
-t ACTION NUMBER PARAM, --triplet ACTION NUMBER PARAM
$ ./triplet.py -t action1 number1 param1
Namespace(triplet=[['action1', 'number1', 'param1']])
$ ./triplet.py -t action1 number1 param1 -t action2 number2 param2
Namespace(triplet=[['action1', 'number1', 'param1'], ['action2', 'number2', 'param2']])