杰瑞科技汇

Python如何添加命令行参数?

Of course! In Python, "adding an argument" can mean several different things depending on the context. I'll cover the three most common scenarios:

Python如何添加命令行参数?-图1
(图片来源网络,侵删)
  1. Adding an Argument to a Function Definition (Creating the function)
  2. Passing an Argument to a Function Call (Using the function)
  3. Adding Command-Line Arguments to a Script (Using the argparse module)

Adding an Argument to a Function Definition

This is about defining a function that accepts input. You add arguments by placing them inside the parentheses after the function name.

Syntax:

def function_name(argument1, argument2, ...):
    # Code that uses the arguments
    return result

Example:

Let's create a function greet_user that takes one argument, name.

Python如何添加命令行参数?-图2
(图片来源网络,侵删)
def greet_user(name):
    """This function greets the person passed in as an argument."""
    print(f"Hello, {name}!")
# You can now call this function and pass a value for the 'name' argument.
greet_user("Alice")  # Output: Hello, Alice!
greet_user("Bob")    # Output: Hello, Bob!

You can add more arguments by separating them with a comma.

Example with Multiple Arguments:

Here's a function add_numbers that takes two arguments, a and b.

def add_numbers(a, b):
    """This function returns the sum of two numbers."""
    return a + b
# Call the function and pass two arguments
sum_result = add_numbers(5, 3)
print(f"The sum is: {sum_result}")  # Output: The sum is: 8

Passing an Argument to a Function Call

This is the act of using a function you've already defined. You provide the actual values (called arguments or parameters) for the function's parameters.

Python如何添加命令行参数?-图3
(图片来源网络,侵删)

How it works:

The value you pass in the function call is assigned to the parameter in the function definition.

Example:

# Function definition with two parameters: 'x' and 'y'
def describe_pet(animal_type, pet_name):
    """Display information about a pet."""
    print(f"\nI have a {animal_type}.")
    print(f"Its name is {pet_name.title()}.")
# --- Function Calls (Passing Arguments) ---
# Positional Arguments: The order matters!
# The first argument "hamster" is assigned to 'animal_type'.
# The second argument "wille" is assigned to 'pet_name'.
describe_pet("hamster", "wille")
# Keyword Arguments: The order does NOT matter because you specify the parameter name.
# This is often clearer and less error-prone.
describe_pet(pet_name="harry", animal_type="hamster")

Output:

I have a a hamster.
Its name is Wille.
I have a a hamster.
Its name is Harry.

Adding Command-Line Arguments to a Script

This is for creating powerful command-line tools. You want your Python script to accept arguments directly from the terminal, like python my_script.py input.txt --verbose. The standard way to do this is with the argparse module.

Step-by-Step Guide with argparse:

Let's create a script named process_data.py that accepts an input file and an optional --verbose flag.

Step 1: Import the module and create a parser.

import argparse
# Create the parser object
parser = argparse.ArgumentParser(description="A simple script to process data.")
# Add arguments to the parser

Step 2: Add your arguments.

You'll add two arguments:

  1. A positional argument for the input file (required).
  2. An optional argument for verbose mode (starts with ).
import argparse
parser = argparse.ArgumentParser(description="A simple script to process data.")
# Add a positional argument (required)
# 'help' provides a description for the user.
parser.add_argument(
    "input_file",
    type=str,  # Specifies the type of the argument
    help="The path to the input data file."
)
# Add an optional argument (flag)
# 'action='store_true'' means the argument is a boolean flag.
# If the user includes --verbose, its value will be True. Otherwise, False.
parser.add_argument(
    "--verbose",
    action="store_true",
    help="Enable verbose output."
)
# Parse the arguments from the command line
args = parser.parse_args()

Step 3: Use the parsed arguments in your script.

import argparse
# (Parser and argument definitions from above)
parser = argparse.ArgumentParser(description="A simple script to process data.")
parser.add_argument("input_file", type=str, help="The path to the input data file.")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output.")
args = parser.parse_args()
# --- Now you can use the arguments ---
if args.verbose:
    print(f"Verbose mode is ON.")
    print(f"Processing file: {args.input_file}")
else:
    print(f"Processing file: {args.input_file} (standard mode)")
# Simulate processing
print("Processing complete.")

How to Run the Script:

  1. Save the code above as process_data.py.
  2. Run it from your terminal.

Example 1: Running without the --verbose flag

$ python process_data.py data.txt

Output:

Processing file: data.txt (standard mode)
Processing complete.

Example 2: Running with the --verbose flag

$ python process_data.py data.txt --verbose

Output:

Verbose mode is ON.
Processing file: data.txt
Processing complete.

Example 3: Getting help

The argparse module automatically generates a help message.

$ python process_data.py -h

Output:

usage: process_data.py [-h] [--verbose] input_file
A simple script to process data.
positional arguments:
  input_file    The path to the input data file.
options:
  -h, --help    show this help message and exit
  --verbose     Enable verbose output.

Summary

Context What You Do Example Code
Function Definition Add parameter names inside in the def statement. def my_func(param1, param2):
Function Call Provide values for the parameters when you call the function. my_func("hello", 123)
Command-Line Script Use argparse.ArgumentParser() and parser.add_argument() to define them. parser.add_argument("input_file", help="Path to the file.")
分享:
扫描分享到社交APP
上一篇
下一篇