Skip to content
Advertisement

How can I pass a list as a command-line argument with argparse?

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?

JavaScript

Script is called like below

JavaScript

Advertisement

Answer

SHORT ANSWER

Use the nargs option or the 'append' setting of the action option (depending on how you want the user interface to behave).

nargs

JavaScript

nargs='+' takes 1 or more arguments, nargs='*' takes zero or more.

append

JavaScript

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 use type=list with argparse. 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.

JavaScript

Here is the output you can expect:

JavaScript

Takeaways:

  • Use nargs or action='append'
    • nargs can be more straightforward from a user perspective, but it can be unintuitive if there are positional arguments because argparse can’t tell what should be a positional argument and what belongs to the nargs; if you have positional arguments then action='append' may end up being a better choice.
    • The above is only true if nargs is given '*', '+', or '?'. If you provide an integer number (such as 4) then there will be no problem mixing options with nargs and positional arguments because argparse will know exactly how many values to expect for the option.
  • Don’t use quotes on the command line1
  • Don’t use type=list, as it will return a list of lists
    • This happens because under the hood argparse uses the value of type to coerce each individual given argument you your chosen type, not the aggregate of all arguments.
    • You can use 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement