A way to make arguments repeatable is to use an 'append' action type:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='append')
parser.add_argument('-b', action='append')
parser.add_argument('-c', action='append')
argv = '-a 1 -b 2 -c 3 -a 4 -c 6 -a 7 -b 8 -a 10'
args = parser.parse_args(argv.split())
print args
produces:
Namespace(a=['1', '4', '7', '10'], b=['2', '8'], c=['3', '6'])
Unfortunately it does lose some information. There's no way to associate the '4' with the '6' instead of the '8'.
If you use '--' to separate blocks of arguments, then this iterative parser might do the job:
parser = argparse.ArgumentParser()
# SUPPRESS keeps the default None out of the namespace
parser.add_argument('-a', type=int, default=argparse.SUPPRESS, required=True)
parser.add_argument('-b', type=int, default=argparse.SUPPRESS)
parser.add_argument('-c', type=int, default=argparse.SUPPRESS)
argv = '-a 1 -b 2 -c 3 -- -a 4 -c 6 -- -a 7 -b 8 -- -a 10'
arglist = []
rest = argv.split()
while rest:
args,rest = parser.parse_known_args(rest)
rest = rest[1:] # remove the 1st '--'
print args
arglist.append(vars(args))
print arglist
producing:
Namespace(a=1, b=2, c=3)
Namespace(a=4, c=6)
Namespace(a=7, b=8)
Namespace(a=10)
[{'a': 1, 'c': 3, 'b': 2},
{'a': 4, 'c': 6},
{'a': 7, 'b': 8},
{'a': 10}]
I'm not sure if it is robust enough. I made -a
required, so omitting it from one of the groups will raise an error.
Or adapting farzad's iterator:
def by_sets(iterator, start):
set = []
for val in iterator:
if set and val == start:
yield set
set = [val]
else:
set.append(val)
yield set
argv = '-a 1 -b 2 -c 3 -a 4 -c 6 -a 7 -b 8 -a 10'
# print list(by_sets(argv.split(), '-a'))
# [['-a', '1', '-b', '2', '-c', '3'], ['-a', '4', '-c', '6'],... ['-a', '10']]
arglist = []
for aset in by_sets(argv.split(), '-a'):
arglist.append(vars(parser.parse_args(aset)))
print arglist
produces:
[{'a': 1, 'c': 3, 'b': 2}, {'a': 4, 'c': 6}, {'a': 7, 'b': 8}, {'a': 10}]
The loop can also be written as a comprehension:
[vars(parser.parse_args(aset)) for aset in by_sets(argv.split(), '-a')]