It seems as though it would always make more sense to use the default action of store
without specifying nargs
so the output is always as expected, instead of sometimes being a list
and sometimes not. I'm just curious if I missed something..
example
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('--bar', nargs=1)
_StoreAction(option_strings=['--bar'], dest='bar', nargs=1, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('--foo 1 --bar 1'.split())
Namespace(bar=['1'], foo='1')
>>> parser.parse_args('')
Namespace(bar=None, foo=None)
Using the nargs parameter in add_argument() , you can specify the number (or arbitrary number) of inputs the argument should expect. In this example named sum.py , the --value argument takes in 3 integers and will print the sum.
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv . The argparse module also automatically generates help and usage messages.
Python argparse optional argument The module is imported. An argument is added with add_argument . The action set to store_true will store the argument as True , if present. The help option gives argument help.
parse_args() returns two values: options, an object containing values for all of your options— e.g. if "--file" takes a single string argument, then options. file will be the filename supplied by the user, or None if the user did not supply that option.
Both the default nargs=None
and nargs=1
expect one value, but nargs=1
will put it in a list, e.g.
Namespace(foo='test')
Namespace(foo=['test'])
nargs=3
will require 3 values, and put them in a list as well. *
and +
also put the values in a list.
From the docs, under nargs=N
:
https://docs.python.org/3/library/argparse.html#nargs
Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.
nargs=1
is just an instance of nargs=n
. It's not a special case.
For you, as an argparse
user, you probably don't need to use 1
. In fact to me it's a sign of a novice - unless there's a clear need for the list in the output. I can imagine, for example, building a parser that programmatically sets n
to some number, may be 3, maybe 5, maybe 1, and expects the result to always be a list.
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