I am trying to pass a list as an argument to a command line program. Is there an argparse
option to pass a list as option?
parser.add_argument('-l', '--list',
type=list, action='store',
dest='list',
help='<Required> Set flag',
required=True)
Script is called like below
python test.py -l "265340 268738 270774 270817"
Best Answer
SHORT ANSWER
Use the
nargs
option or the'append'
setting of theaction
option (depending on how you want the user interface to behave).nargs
nargs='+'
takes 1 or more arguments,nargs='*'
takes zero or more.append
With
append
you provide the option multiple times to build up the list.Don't use
type=list
!!! - There is probably no situation where you would want to usetype=list
withargparse
. Ever.LONG ANSWER
Let's take a look in more detail at some of the different ways one might try to do this, and the end result.
Here is the output you can expect:
Takeaways:
nargs
oraction='append'
nargs
can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments becauseargparse
can't tell what should be a positional argument and what belongs to thenargs
; if you have positional arguments thenaction='append'
may end up being a better choice.nargs
is given'*'
,'+'
, or'?'
. If you provide an integer number (such as4
) then there will be no problem mixing options withnargs
and positional arguments becauseargparse
will know exactly how many values to expect for the option.type=list
, as it will return a list of listsargparse
uses the value oftype
to coerce each individual given argument you your chosentype
, not the aggregate of all arguments.type=int
(or whatever) to get a list of ints (or whatever)1: I don't mean in general.. I mean using quotes to pass a list to
argparse
is not what you want.