杰瑞科技汇

如何在Windows CMD中运行Python脚本?

Of course! Let's break down everything you need to know about using Python on the Windows Command Prompt (CMD). We'll cover the basics, essential commands, common tasks, and how to solve frequent problems.

如何在Windows CMD中运行Python脚本?-图1
(图片来源网络,侵删)

Part 1: The Absolute Basics

Opening the Command Prompt (CMD)

There are several ways to open it. The easiest is:

  • Press the Windows Key + R, type cmd, and press Enter.

You can also search for "Command Prompt" in the Start Menu.

Verifying Python is Installed

Before you do anything, you need to make sure Python is installed and that Windows knows where to find it.

  1. In the CMD window, type the following command and press Enter:

    如何在Windows CMD中运行Python脚本?-图2
    (图片来源网络,侵删)
    python --version

    or

    py --version
  2. What to expect:

    • If it works: You will see the installed Python version, like Python 3.11.4.
    • If it fails: You will see an error like 'python' is not recognized as an internal or external command....

The "Python is not recognized" Error (The #1 Problem)

This error means the Python installation directory is not in your system's PATH environment variable. The PATH is a list of directories that Windows searches for when you type a command.

How to Fix It:

如何在Windows CMD中运行Python脚本?-图3
(图片来源网络,侵删)
  1. Find your Python installation path:

    • Open the Start Menu and search for "Edit the system environment variables".
    • Click on "Environment Variables...".
    • In the "System variables" section (the bottom half), find the variable named Path and click "Edit...".
    • You need to find the path to your Python executable. It will look something like this:
      • C:\Users\YourUsername\AppData\Local\Programs\Python\Python311\
      • C:\Python39\
    • You also need the path to the Scripts folder inside that directory:
      • C:\Users\YourUsername\AppData\Local\Programs\Python\Python311\Scripts\
  2. Add the paths to the Path variable:

    • In the "Edit environment variable" window, click "New" and paste the path to your Python main folder (e.g., C:\Python39).
    • Click "New" again and paste the path to your Scripts folder (e.g., C:\Python39\Scripts).
    • Important: Make sure these paths appear before any other conflicting paths.
    • Click "OK" on all the windows to save.
  3. Test it again:

    • Close your Command Prompt window and open a new one. This is crucial!
    • Run python --version again. It should now work.

Part 2: Essential Python Commands in CMD

Here are the most common things you'll do.

Running a Python Script

Let's say you have a file named hello.py with this content:

# hello.py
print("Hello from Python!")
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")

To run it from your CMD:

  1. Navigate to the directory where hello.py is located using the cd (change directory) command.
    # Example: If your file is in C:\Users\YourName\Documents
    cd C:\Users\YourName\Documents
  2. Run the script using the python command.
    python hello.py

Output:

Hello from Python!
What is your name? Alice
Nice to meet you, Alice!

The Interactive Python Shell

This is like a calculator for code. You can type Python commands and see the results immediately.

  1. In CMD, simply type python and press Enter.
    python
  2. You'll see the Python version and a >>> prompt.
    Python 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2025, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
  3. Now you can type Python code directly:
    >>> 2 + 2
    4
    >>> print("Hello, world!")
    Hello, world!
    >>> my_list = [1, 2, 3]
    >>> my_list.append(4)
    >>> my_list
    [1, 2, 3, 4]
  4. To exit the shell, type exit() or press Ctrl + Z followed by Enter.

Using pip (Python's Package Installer)

pip is used to install third-party libraries from the Python Package Index (PyPI).

  • Install a package:
    # Install the popular 'requests' library
    pip install requests
  • Upgrade a package:
    pip install --upgrade requests
  • Uninstall a package:
    pip uninstall requests
  • List installed packages:
    pip list
  • Show information about a package:
    pip show requests

Part 3: Common Tasks and Tips

Navigating the File System

These commands work in CMD just like in any other terminal.

Command Description Example
dir List files and folders in the current directory. dir
cd <path> Change to a different directory. cd C:\MyProjects
cd .. Go up one directory level. cd ..
mkdir <name> Make a new directory. mkdir new_folder
del <file> Delete a file. del old_file.txt
rmdir <dir> Remove a directory (must be empty). rmdir empty_folder

Virtual Environments (Best Practice!)

A virtual environment is an isolated space for a Python project. It prevents conflicts between different projects' dependencies.

  1. Navigate to your project folder:

    cd C:\MyProjects\my_awesome_app
  2. Create the virtual environment:

    • The modern and recommended way is to use the venv module that comes with Python.
      # Creates a folder named 'venv' with the environment inside
      python -m venv venv
    • If that doesn't work, you can try the older virtualenv package (you may need to install it first with pip install virtualenv):
      virtualenv venv
  3. Activate the environment:

    • This is the most important step. You must do this every time you work on the project.
      venv\Scripts\activate
    • You will know it's active because your command prompt will be prefixed with (venv):
      (venv) C:\MyProjects\my_awesome_app>
  4. Work inside the environment:

    • Now, when you install packages, they will go only into this venv folder, not your global Python installation.
      (venv) C:\MyProjects\my_awesome_app> pip install requests pandas
  5. Deactivate the environment:

    • When you're done, simply type:
      (venv) C:\MyProjects\my_awesome_app> deactivate
    • The (venv) prefix will disappear from your prompt.

Part 4: CMD vs. PowerShell vs. Python Launcher (py)

Tool Description When to Use
CMD (Command Prompt) The original, simple Windows command line. Good for basic file operations and running scripts. General-purpose, quick tasks, simple scripts.
PowerShell A modern, more powerful command-line shell and scripting language from Microsoft. Advanced system administration, complex scripting, object-oriented output.
Python Launcher (py) A tool specifically for running Python versions. It's the most robust way to run Python. This is the recommended way to run Python. It handles version selection (e.g., py -3.11) and is less likely to be confused by other tools.

Best Practice: Instead of python your_script.py, use the launcher:

py your_script.py

This ensures you are running the Python version you intend, even if multiple versions are installed. You can also specify a version: py -3 your_script.py.

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