杰瑞科技汇

Python命令行如何高效开发与调试?

Of course! The Python command line is a powerful tool for both running scripts and using Python interactively. Let's break it down into its main components.

Python命令行如何高效开发与调试?-图1
(图片来源网络,侵删)

The Interactive Interpreter (REPL)

When you type python in your terminal and press Enter, you enter the Read-Eval-Print Loop (REPL). It's an interactive shell where you can type Python code and see the results immediately.

How to start it: Open your terminal (Command Prompt, PowerShell, Terminal, etc.) and type:

python

or, if you have multiple Python versions:

python3

What it looks like:

Python命令行如何高效开发与调试?-图2
(图片来源网络,侵删)
Python 3.10.4 (main, Jun 29 2025, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

The >>> is the prompt, waiting for your input.

Example session:

>>> print("Hello, World!")
Hello, World!
>>> 2 + 2
4
>>> my_variable = "This is a test"
>>> my_variable
'This is a test'
>>> help(len)
Help on built-in function len in module builtins:
len(obj, /)
    Return the number of items in a container.
>>> exit()

To exit the REPL, you can type exit() or press Ctrl+D (on Linux/macOS) or Ctrl+Z then Enter (on Windows).


Executing Python Scripts

This is the most common use case. You have a file (e.g., my_script.py) and you want to run it from the command line.

Python命令行如何高效开发与调试?-图3
(图片来源网络,侵删)

The Basic Command The fundamental syntax is:

python your_script.py

Example Script (my_script.py):

# my_script.py
import sys
import os
print("Script started.")
print(f"The first argument is: {sys.argv[0]}") # The script name itself
print(f"The script's current working directory is: {os.getcwd()}")
if len(sys.argv) > 1:
    print(f"You provided an argument: {sys.argv[1]}")
else:
    print("No arguments were provided.")
print("Script finished.")

How to Run It:

  1. Save the code above as my_script.py.

  2. Open your terminal in the same directory.

  3. Run the script:

    python my_script.py

    Output:

    Script started.
    The first argument is: my_script.py
    The script's current working directory is: /path/to/your/directory
    No arguments were provided.
    Script finished.
  4. Now, run it with an argument:

    python my_script.py hello

    Output:

    Script started.
    The first argument is: my_script.py
    The script's current working directory is: /path/to/your/directory
    You provided an argument: hello
    Script finished.

Command-Line Arguments and sys.argv

Your Python script can receive arguments from the command line. These arguments are stored in a list called sys.argv.

  • sys.argv[0] is always the name of the script itself.
  • sys.argv[1] is the first actual argument you provide.
  • sys.argv[2] is the second, and so on.

Example (argument_parser.py):

# argument_parser.py
import sys
print(f"Total number of arguments: {len(sys.argv)}")
print(f"Argument List: {str(sys.argv)}")
# A simple loop to print all arguments
print("\n--- Looping through arguments ---")
for i, arg in enumerate(sys.argv):
    print(f"Argument {i}: {arg}")

Running it:

python argument_parser.py apples oranges "bananas and grapes"

Output:

Total number of arguments: 4
Argument List: ['argument_parser.py', 'apples', 'oranges', 'bananas and grapes']
--- Looping through arguments ---
Argument 0: argument_parser.py
Argument 1: apples
Argument 2: oranges
Argument 3: bananas and grapes

Note: If an argument has spaces, you must wrap it in quotes ( or ).


The Standard Way: Using argparse

While sys.argv is great for simple scripts, Python's built-in argparse module is the standard and much more powerful way to handle command-line arguments. It automatically generates help messages, handles data types, and manages flags.

Example (argparse_example.py):

# argparse_example.py
import argparse
# 1. Create the parser object
parser = argparse.ArgumentParser(description="A simple calculator script.")
# 2. Add arguments
# 'x' and 'y' are positional arguments (required)
# 'action' is an optional flag
parser.add_argument("x", type=float, help="The first number.")
parser.add_argument("y", type=float, help="The second number.")
parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output.")
# 3. Parse the arguments
args = parser.parse_args()
# 4. Use the arguments
result = args.x + args.y
if args.verbose:
    print(f"Calculating {args.x} + {args.y}...")
    print(f"The result is: {result}")
else:
    print(result)

How to Run It:

  • Get the help message (very useful!):

    python argparse_example.py -h

    Output:

    usage: argparse_example.py [-h] [-v] x y
    A simple calculator script.
    positional arguments:
      x           The first number.
      y           The second number.
    options:
      -h, --help  show this help message and exit
      -v, --verbose
                    Enable verbose output.
  • Run it normally:

    python argparse_example.py 5 10

    Output:

    0
  • Run it with the verbose flag:

    python argparse_example.py -v 5 10

    Output:

    Calculating 5.0 + 10.0...
    The result is: 15.0

Other Useful Command-Line Options

Here are some other common flags you can use with the python command.

Flag Description Example
-c <command> Executes the Python command given in the string and then exits. Great for quick, one-liners. python -c "import random; print(random.randint(1, 100))"
-m <module> Runs a module as a script. This is how you run tools like pip or http.server. python -m pip install requests
python -m http.server 8000
--version Prints the Python version and exits. python --version
-O Runs Python in optimized mode (.pyc files are generated, assert statements are removed). python -O my_script.py
-i Runs the script and then enters the interactive interpreter. Useful for debugging. python -i my_script.py

Setting Up a Virtual Environment (Best Practice)

Before installing packages for a project, you should always use a virtual environment. It isolates your project's dependencies from your system's global Python installation.

Steps:

  1. Create a virtual environment (it's common to name it venv):

    python -m venv venv

    This creates a venv folder containing a separate Python interpreter and packages.

  2. Activate the environment:

    • On macOS/Linux:
      source venv/bin/activate
    • On Windows (Command Prompt):
      venv\Scripts\activate
    • On Windows (PowerShell):
      .\venv\Scripts\Activate.ps1

      Your terminal prompt will change to show (venv), indicating the environment is active.

  3. Now, when you run python or pip, it uses the isolated versions from the venv:

    (venv) $ pip install requests
    (venv) $ python my_script.py
  4. Deactivate the environment when you're done:

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