杰瑞科技汇

addargument在Python中如何使用?

Of course! The term add_argument is central to Python's argparse module, which is the standard way to create command-line interfaces for your scripts.

Let's break it down from a simple explanation to a comprehensive guide.

What is add_argument?

In simple terms, add_argument() is a function that you use to define the command-line arguments your script can accept. You call it on an ArgumentParser object.

Each time you call parser.add_argument(), you are telling the parser:

  • What the argument is called (e.g., --input or -i).
  • What kind of value it expects (e.g., a string, a number, a boolean flag).
  • What to do with that value (e.g., store it in a variable, print a message).

The Basic Workflow

To use argparse, you follow these three steps:

  1. Import the module:

    import argparse
  2. Create an ArgumentParser object: This object will hold all the information about your script's arguments.

    parser = argparse.ArgumentParser(description='A simple script to demonstrate add_argument.')
  3. Define arguments using add_argument(): This is the core of the process.

    parser.add_argument('--name', help='The name to greet.')
  4. Parse the arguments: This line reads the arguments provided by the user on the command line and turns them into a usable object.

    args = parser.parse_args()
  5. Use the parsed arguments: The arguments are stored as attributes on the args object.

    if args.name:
        print(f"Hello, {args.name}!")

Full Example: A Simple Greeting Script

Let's put it all together in a file named greet.py.

# greet.py
import argparse
# 1. Create the parser
parser = argparse.ArgumentParser(description="Greets a user by name.")
# 2. Add an argument
# --name is a long-form argument (e.g., --name Alice)
# -n is a short-form, single-letter alias (e.g., -n Alice)
# 'The name to greet' is the help message shown when you run --help
parser.add_argument('--name', '-n', help='The name to greet.')
# 3. Parse the arguments
args = parser.parse_args()
# 4. Use the parsed arguments
if args.name:
    print(f"Hello, {args.name}!")
else:
    print("Hello, stranger!")

How to Run It:

Run with --help: This is the most important feature. It shows you how to use your script.

$ python greet.py --help

Output:

usage: greet.py [-h] [--name NAME | -n NAME]
Greets a user by name.
options:
  -h, --help  show this help message and exit
  --name NAME, -n NAME
              The name to greet.

Run with the --name argument:

$ python greet.py --name "Alice"

Output:

Hello, Alice!

Run with the short -n argument:

$ python greet.py -n "Bob"

Output:

Hello, Bob!

Run with no argument:

$ python greet.py

Output:

Hello, stranger!

Key Features and Common add_argument() Options

Here are the most useful things you can do with add_argument().

Specifying the Type of Argument

By default, all arguments are strings. You can change this with the type parameter.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--count', type=int, help='An integer count.')
parser.add_argument('--price', type=float, help='A floating-point price.')
args = parser.parse_args()
if args.count:
    print(f"The count is: {args.count} (type: {type(args.count)})")
if args.price:
    print(f"The price is: {args.price} (type: {type(args.price)})")

Usage:

$ python script.py --count 10 --price 19.99

Output:

The count is: 10 (type: <class 'int'>)
The price is: 19.99 (type: <class 'float'>)

Boolean Flags (Actions)

For flags that are either present or not present (like --verbose), use the action parameter.

  • store_true: The argument is set to True if the flag is present, and False otherwise.
  • store_false: The opposite of store_true.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose mode.')
parser.add_argument('--quiet', action='store_false', dest='verbose', help='Disable verbose mode.')
args = parser.parse_args()
if args.verbose:
    print("Verbose mode is ON. Printing detailed logs.")
else:
    print("Verbose mode is OFF.")

Usage:

$ python script.py --verbose

Output:

Verbose mode is ON. Printing detailed logs.
$ python script.py

Output:

Verbose mode is OFF.

Required Arguments

To make an argument mandatory, set required=True.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input-file', '-i', required=True, help='The input file to process.')
args = parser.parse_args()
print(f"Processing file: {args.input_file}")

Usage:

$ python script.py --input-file data.txt

Output:

Processing file: data.txt

If you try to run it without the argument, argparse will automatically show an error and the help message.

Choosing from a List of Options

If an argument must be one of a specific set of values, use choices.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--log-level', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], help='Set the logging level.')
args = parser.parse_args()
if args.log_level:
    print(f"Log level set to: {args.log_level}")

Usage:

$ python script.py --log-level INFO

Output:

Log level set to: INFO

If you try an invalid choice like --log-level NOTICE, argparse will show an error.

Storing Multiple Values (Lists)

If you want to accept the same argument multiple times, use nargs='+' (one or more) or nargs='*' (zero or more).

import argparse
parser = argparse.ArgumentParser()
# nargs='+' means the user must provide at least one file
parser.add_argument('--files', nargs='+', help='One or more input files to process.')
args = parser.parse_args()
print(f"Files to process: {args.files}")

Usage:

$ python script.py --files file1.txt file2.txt file3.log

Output:

Files to process: ['file1.txt', 'file2.txt', 'file3.log']

Setting a Default Value

Use the default parameter to provide a fallback value if the argument is not supplied.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int, default=8080, help='The port to listen on (default: 8080).')
args = parser.parse_args()
print(f"Server will start on port: {args.port}")

Usage:

# Using the default value
$ python script.py

Output:

Server will start on port: 8080
# Overriding the default
$ python script.py --port 3000

Output:

Server will start on port: 3000

Summary Table

Parameter Description Example
name_or_flags (Required) The name or flags for the argument. parser.add_argument('--input', '-i')
help A brief description of the argument. help='Input file path'
type The type to which the argument should be converted. type=int, type=float
action How the argument should be handled. action='store_true', action='store_false'
required Whether the argument is required. required=True
choices A container of the allowable values for the argument. choices=['a', 'b', 'c']
nargs The number of command-line arguments that should be consumed. nargs='?', nargs='*', nargs='+'
default The value produced if the argument is absent. default=10

Mastering add_argument is a key skill for writing professional, user-friendly, and powerful command-line tools in Python.

分享:
扫描分享到社交APP
上一篇
下一篇