杰瑞科技汇

Python main.py 80 参数如何传递?

Of course. Running a Python script like main.py with a command-line argument 80 is a very common task. Here’s a complete guide on how to do it, from the basic command to how to handle the argument inside your script.

Python main.py 80 参数如何传递?-图1
(图片来源网络,侵删)

The Basic Command

To run your script from the terminal or command prompt, you use the python command followed by the script name and then the argument.

python main.py 80

How it works:

  • python: The command to start the Python interpreter.
  • main.py: The name of your Python script file.
  • 80: This is a command-line argument. It's passed to your script as a string.

How to Access the Argument in main.py

Your script needs to be able to read the arguments passed to it. Python has a built-in module for this called sys.

The arguments are stored in a list called sys.argv.

Python main.py 80 参数如何传递?-图2
(图片来源网络,侵删)
  • sys.argv[0] is always the name of the script itself (main.py).
  • sys.argv[1] is the first argument you provided (80).
  • sys.argv[2] would be the second argument, and so on.

Example main.py

Here is a simple main.py that receives the argument and prints it.

# main.py
import sys
# Check if an argument was provided
if len(sys.argv) > 1:
    # The first argument (at index 1) is the port number
    port_arg = sys.argv[1]
    # The argument is a string, so you should convert it to an integer
    try:
        port_number = int(port_arg)
        print(f"Script received the port number: {port_number}")
        print(f"Type of port_number is: {type(port_number)}")
        # You can now use port_number in your application
        if 1024 <= port_number <= 49151:
            print(f"Port {port_number} is in the registered port range.")
        else:
            print(f"Port {port_number} is not in the registered port range.")
    except ValueError:
        print(f"Error: The argument '{port_arg}' is not a valid integer.")
else:
    print("Error: No argument provided.")
    print("Usage: python main.py <port_number>")

How to Run It

  1. Save the code above as main.py.

  2. Open your terminal or command prompt.

  3. Navigate to the directory where you saved the file.

    Python main.py 80 参数如何传递?-图3
    (图片来源网络,侵删)
  4. Run the command:

    python main.py 80

Expected Output

Script received the port number: 80
Type of port_number is: <class 'int'>
Port 80 is not in the registered port range.

A More Robust Way: Using argparse

For more complex scripts, manually handling sys.argv can be tedious and error-prone. The argparse module is the standard, more powerful way to handle command-line arguments. It automatically generates help messages and handles errors for you.

Example main.py with argparse

This version is more robust and user-friendly.

# main.py
import argparse
# Create the parser
parser = argparse.ArgumentParser(
    description="A simple script that takes a port number as an argument."
)
# Add an argument for the port number
# -p or --port are the flags to use it
# type=int ensures it's converted to an integer
# required=True means this argument must be provided
parser.add_argument(
    "-p", 
    "--port", 
    type=int, 
    required=True, 
    help="The port number to use (e.g., 8080)"
)
# Parse the arguments provided by the user
args = parser.parse_args()
# Now you can access the port number using args.port
port_number = args.port
print(f"Script received the port number: {port_number}")
print(f"Type of port_number is: {type(port_number)}")
# Example of using the port number
if 1024 <= port_number <= 49151:
    print(f"Port {port_number} is in the registered port range.")
else:
    print(f"Port {port_number} is not in the registered port range.")

How to Run It

  1. Save the code above as main.py.
  2. Open your terminal and run the script.

Correct Usage:

python main.py --port 80
# or using the short flag
python main.py -p 80

Expected Output (same as before):

Script received the port number: 80
Type of port_number is: <class 'int'>
Port 80 is not in the registered port range.

Getting Help (a major advantage of argparse): If you run the script with the -h or --help flag, argparse automatically generates a help message.

python main.py -h

Expected Output:

usage: main.py [-h] -p PORT
A simple script that takes a port number as an argument.
options:
  -h, --help  show this help message and exit
  -p PORT     The port number to use (e.g., 8080)

Error Handling: If you forget a required argument, argparse gives a clear error.

python main.py

Expected Output:

usage: main.py [-h] -p PORT
main.py: error: the following arguments are required: -p/--port

Summary

Method Pros Cons Best For
sys.argv Simple, built-in, no imports needed. Manual error handling, no automatic help, parsing is basic. Quick and simple scripts with one or two arguments.
argparse Powerful, automatic help/error messages, supports flags, optional/required args, data types. Slightly more code to set up. Almost all non-trivial command-line applications.
分享:
扫描分享到社交APP
上一篇
下一篇