Home > Backend Development > Python Tutorial > How do I pass a list of arguments to a Python script using argparse?

How do I pass a list of arguments to a Python script using argparse?

DDD
Release: 2024-10-28 00:26:29
Original
793 people have browsed it

How do I pass a list of arguments to a Python script using argparse?

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

Command-Line Argument Passing in argparse

When seeking to furnish argparse with a list of arguments, it's crucial to understand that type=list should be avoided. Instead, employ either the nargs option or action='append'.

The nargs Option

Usage:

Example:

<code class="python">python arg.py -l 1234 2345 3456 4567</code>
Copy after login

Interpretation:

  • nargs=' ' indicates the acceptance of one or more arguments.
  • nargs='*' accepts zero or more arguments.
  • nargs='?' accepts zero or one argument.
  • An integer value for nargs specifies the precise number of arguments to accept.

The append Action

Usage:

Example:

<code class="python">python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567</code>
Copy after login

Interpretation:

  • action='append' requires specifying the flag multiple times to construct a list.

Input Handling in argparse

  • argparse can interpret negative numbers as expected.
  • Quotes should not be used on the command line when providing lists to argparse.

The above is the detailed content of How do I pass a list of arguments to a Python script using argparse?. 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