"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-06
Browse:964

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:

parser.add_argument('-l', '--list', nargs=' ', help=' Set flag', required=True)
# Use like:
# python test.py -l 1234 2345 3456 4567

append

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

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

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3