python argh/argparse: How can I pass a list as a command-line argument?
With argparse
, you just use type=int
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--arg', nargs='+', type=int)
print parser.parse_args()
Example output:
$ python test.py -a 1 2 3
Namespace(arg=[1, 2, 3])
Edit: I'm not familiar with argh
, but it seems to be just a wrapper around argparse
and this worked for me:
import argh
@argh.arg('-a', '--arg', nargs='+', type=int)
def main(args):
print args
parser = argh.ArghParser()
parser.add_commands([main])
parser.dispatch()
Example output:
$ python test.py main -a 1 2 3
Namespace(arg=[1, 2, 3], function=<function main at 0x.......>)
I order to have access to each parameter value, the following code may be helpful.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--arg', nargs='+', type=int)
args = vars(parser.parse_args())
print "first parameter:" + str(args["arg"][0])
print "second parameter:" + str(args["arg"][1])
print "third parameter:" + str(args["arg"][2])