Home >Backend Development >Python Tutorial >How can I pass a list of values as a command-line argument using Python\'s argparse module?

How can I pass a list of values as a command-line argument using Python\'s argparse module?

DDD
DDDOriginal
2024-11-01 17:05:03344browse

How can I pass a list of values as a command-line argument using Python's argparse module?

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

In Python's argparse module, you can pass a list as a command-line argument using the nargs or append options.

nargs

Use nargs to specify the number of arguments to expect. For example, nargs=' indicates one or more arguments, and nargs='*' indicates zero or more arguments. Here's how to use it:

<code class="python">parser.add_argument('-l', '--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python test.py -l 1234 2345 3456 4567</code>

append

Use append to create a list by adding each argument as an element. Here's how to use it:

<code class="python">parser.add_argument('-l', '--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python test.py -l 1234 -l 2345 -l 3456 -l 4567</code>

IMPORTANT:

  • Do not use type=list with argparse. It creates a list of lists which is not the desired behavior.
  • When passing a list as an argument, avoid using quotes.

The above is the detailed content of How can I pass a list of values as a command-line argument using Python\'s argparse module?. 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