I just noticed a behavior in argparse that puzzled me (guess I'd never used it for a dumb list of files before):
import argparse parser = argparse.ArgumentParser() parser.add_argument('multi', action='append', nargs='+') print(parser.parse_args())
This gives me the output:
~$ ./testargs.py foo bar baz Namespace(multi=[['foo', 'bar', 'baz']]) ~$
I expected multi
to be ['foo', 'bar', 'baz']
, not a list within a list. As-is, I'll have to grab args.multi[0]
before processing, which isn't a big deal, but feels like an ugly wart, and I'd like to understand why it's there.
Am I doing something silly in add_argument
, or is this just an unavoidable quirk?
Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.
dest is equal to the first argument supplied to the add_argument() function, as illustrated. The second argument, radius_circle , is optional. A long option string --radius supplied to the add_argument() function is used as dest , as illustrated.
The argparse is a standard module; we do not need to install it. A parser is created with ArgumentParser and a new parameter is added with add_argument .
You are calling
parser.add_argument('multi', action='append', nargs='+')
And it is taking all the arguments and appending as a single item in the multi list.
If you want it as individual items, just don't use append
parser.add_argument('multi', nargs='+')
From the docs
'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:
>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='append') >>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With