Home  >  Article  >  Backend Development  >  How Do I Pass a List as an Argument to a Command-Line Program Using argparse?

How Do I Pass a List as an Argument to a Command-Line Program Using argparse?

DDD
DDDOriginal
2024-10-28 05:30:02974browse

How Do I Pass a List as an Argument to a Command-Line Program Using argparse?

Passing Lists as Arguments in argparse

When attempting to pass a list as an argument to a command-line program using argparse, it's essential to understand the available options for representing lists within the parser.

Not Recommended: Using type=list

Avoid using type=list with argparse as it can lead to incorrect results. It will return a list of lists, not a single list containing the desired elements.

Use nargs for Required Arguments

The nargs parameter allows you to specify the number of arguments an option accepts. To pass a list as a required argument, use:

<code class="python">parser.add_argument('-l', '--list', nargs='+', help='Set flag', required=True)</code>

Use action='append' for Optional Arguments

For optional arguments, use action='append' to allow providing multiple instances of the argument.

<code class="python">parser.add_argument('-l', '--list', action='append', help='Set flag')</code>

Syntax for Invoking These Options

For nargs, the arguments should be provided together without spaces, such as:

<code class="bash">python test.py -l 12345678</code>

For action='append', the argument should be provided multiple times, such as:

<code class="bash">python test.py -l 1234 -l 5678</code>

Additional Considerations

  • Don't use quotes when passing arguments to argparse on the command line.
  • If you want the list elements to be type-converted (e.g., to integers), use type=int within the nargs setting.
  • nargs with or * allows 1 or more arguments, respectively, and ? allows 0 or 1 arguments. For a specific number of arguments, provide an integer to nargs.

The above is the detailed content of How Do I Pass a List as an Argument to a Command-Line Program Using argparse?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn