杰瑞科技汇

Python命令行工具有哪些?

Of course! The Python command line is a fundamental tool for developers. It can mean two main things, and I'll cover both in detail:

Python命令行工具有哪些?-图1
(图片来源网络,侵删)
  1. The Python Interactive Interpreter: A "live" environment where you can type Python code and see the results immediately. It's perfect for testing small snippets of code, debugging, and quick calculations.
  2. Running Python Scripts from Your System's Terminal (or Command Prompt): Executing a complete Python file (.py) from your operating system's command line (like Command Prompt on Windows or Terminal on macOS/Linux).

Part 1: The Python Interactive Interpreter

This is what you get when you simply type python in your terminal.

How to Start It

  1. Open your Terminal/Command Prompt:

    • Windows: Search for cmd or PowerShell.
    • macOS: Open the Terminal app (you can find it in Applications > Utilities or search with Spotlight).
    • Linux: Open your distribution's terminal application (e.g., gnome-terminal, konsole).
  2. Type python or python3:

    • On many systems, python might point to an older Python 2. It's best practice to use python3 to ensure you're using the modern version.
    # On Windows
    py  # This is often the recommended command on Windows
    # or
    python
    # On macOS/Linux
    python3
  3. You'll see the Python prompt:

    Python命令行工具有哪些?-图2
    (图片来源网络,侵删)
    Python 3.9.7 (default, Sep 10 2025, 14:59:43) 
    [Clang 12.0.5 (clang-1205.0.22.9)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 

    The >>> is the prompt, telling you Python is ready for your input.

Basic Commands Inside the Interpreter

  • Execute a simple expression:

    >>> 2 + 2
    4
    >>> print("Hello, World!")
    Hello, World!
  • Assign a variable and use it:

    >>> name = "Alice"
    >>> print(f"Hello, {name}!")
    Hello, Alice!
  • Get help on a function or object:

    Python命令行工具有哪些?-图3
    (图片来源网络,侵删)
    >>> help(print)
    Help on built-in function print in module builtins:
    print(...)
        print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
        Prints the values to a stream, or to sys.stdout by default.
        ...
  • Use exit() or quit() to leave the interpreter:

    >>> exit()
    C:\Users\YourUser>

Part 2: Running Python Scripts from the Command Line

This is how you execute your Python programs.

Step 1: Create a Python File

Create a file named hello.py and add the following code to it using a text editor (like VS Code, Sublime Text, Notepad, etc.).

# hello.py
import time
import sys
print("Hello from a script!")
print("The script name is:", sys.argv[0]) # The script's own name
print(f"Python version: {sys.version}")
# A simple loop
for i in range(5):
    print(f"Count: {i}")
    time.sleep(1)

Step 2: Navigate to the File's Directory in Your Terminal

You need to tell your terminal where to find the file. Use the cd (change directory) command.

  • On macOS/Linux:

    # Replace /path/to/your/folder with the actual path
    cd /Users/YourUser/Documents/PythonProjects
  • On Windows:

    # Replace C:\path\to\your\folder with the actual path
    cd C:\Users\YourUser\Documents\PythonProjects

Step 3: Run the Script

Use the python or python3 command followed by the filename.

# The standard way
python3 hello.py

Expected Output

You will see the output directly in your terminal:

Hello from a script!
The script name is: hello.py
Python version: 3.9.7 (default, Sep 10 2025, 14:59:43) 
[Clang 12.0.5 (clang-1205.0.22.9)]
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

Common Command-Line Options and Arguments

This is where the command line becomes incredibly powerful. You can pass information to your script when you run it.

Command-Line Arguments

You can pass arguments to your script, which are accessible in the sys.argv list.

Modify hello.py:

# hello_args.py
import sys
# sys.argv is a list containing the script name and all arguments
print(f"Number of arguments: {len(sys.argv)}")
print(f"Argument List: {str(sys.argv)}")
# Accessing individual arguments
if len(sys.argv) > 1:
    print(f"Hello, {sys.argv[1]}!")
else:
    print("Hello, stranger!")

Run it from the command line:

python3 hello_args.py Alice

Output:

Number of arguments: 2
Argument List: ['hello_args.py', 'Alice']
Hello, Alice!

Common Python Command-Line Flags

You can add special flags to the python command itself.

  • -c (execute code): Runs a specific string of Python code.

    # This will print the Python version without starting an interactive session
    python3 -c "import sys; print(sys.version_info)"

    Output:

    sys.version_info(major=3, minor=9, micro=7, releaselevel='final', serial=0)
  • -m (run module): Runs a module as a script. This is essential for many standard library tools like pip and venv.

    # This is the correct way to upgrade pip
    python3 -m pip install --upgrade pip
    # This is how you create a virtual environment
    python3 -m venv myenv
  • -v (verbose): Prints a verbose log, useful for debugging imports.

    python3 -v hello.py

    Output (partial):

    # ... lots of info about which modules are being loaded ...
    import sys # precompiled from C:\Python39\lib\sys.py
    import time # precompiled from C:\Python39\lib\time.py
    Hello from a script!
    ...
  • --version or -V: Prints the Python version and exits.

    python3 --version
    # or
    python3 -V

    Output:

    Python 3.9.7

Summary Table

Task Command Description
Start Interactive Shell python3 Opens a live Python environment.
Run a Script python3 my_script.py Executes the code in my_script.py.
Pass an Argument python3 my_script.py arg1 Passes arg1 to the script.
Run a String of Code python3 -c "print('hi')" Executes the code in the quotes.
Run a Module python3 -m pip list Runs the pip module as a script.
Check Version python3 --version Prints the installed Python version.

Tips for Windows Users

  • Use py: The py launcher is the modern, recommended way to manage Python versions on Windows. It's smart enough to find your Python installations.
    • py -> starts the default Python.
    • py -3 -> starts the default Python 3.
    • py -2 -> starts the default Python 2.
    • py -3.9 -> starts a specific Python 3.9 version if installed.
  • PowerShell: PowerShell is more powerful than the old Command Prompt. It has better tab completion and a more modern scripting syntax. You can use all the commands above in PowerShell as well.
分享:
扫描分享到社交APP
上一篇
下一篇