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
Release: 2024-11-01 17:05:03
Original
382 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template