Whether you’re writing your own Python code or running existing scripts on a Windows PC, this guide shows you how to run a Python file from the Windows Command Prompt. It’s a simple process once Python is installed, and you’ll also learn how to fix common errors like “python is not recognized as an internal or external command” or “Python was not found.”

开始之前:确保 Python 已安装在您的 Windows PC 上。

如何在 Windows 上从命令提示符运行 Python 脚本

如果 Python 无法识别,请按照以下详细步骤执行脚本或修复 PATH 问题。

运行 Python 脚本

  • 查找Python 文件的完整路径:
    • 打开文件资源管理器
    • 导航到包含 Python 文件的文件夹。
    • 右键单击该文件并选择属性
    • 复制位置旁边的路径,方法是突出显示该路径并按 Ctrl + C
  • OpenCommand Prompt by pressing the Windows key, typing cmd, and selecting the app.
  • Switch to the script’s directory by typing cd followed by a space, then pasting the full path with Ctrl + V and pressing Enter.
  • 键入python,后跟文件名,例如 python script.py,然后按 Enter 运行它。
    • 如果文件名包含空格,请将其用引号引起来,例如 python “my script.py”
  在任何设备上注销 YouTube 的简单方法

将 Python 添加到 PATH(如果需要)

  • 启用文件资源管理器中查看隐藏文件夹:
    • 点击查看选项卡。
    • 在 Windows 11 中,选择显示 >隐藏项目
    • 在 Windows 10 上,选中隐藏项目复选框。
  • Locate and copy the Python installation path (typically C:\Users\<yourusername>\AppData\Local\Programs\Python\Python38 or similar):
    • 文件资源管理器中,转到这台电脑> your hard drive > 用户> your username > 应用程序数据>本地>程序 >Python > > the version folder.
    • 点击顶部的地址栏将其突出显示,然后按 Ctrl + C
  • 打开系统属性,方法是按Windows 键,输入sysdm.cpl,然后按Enter
  • 点击高级选项卡。
  • 点击环境变量
  • 用户变量下,双击路径
  • 点击新建
  • 使用 Ctrl + V粘贴Python 路径。
  • 在所有打开的对话框中点击确定以保存更改。
  • 重新启动 Windows 以应用更改。现在您可以使用 python 运行脚本。
专业提示:为您的 Python 脚本创建一个专用文件夹,并将其添加到您的 PATH 中,以便从命令提示符中的任何位置更快地访问。

成功运行第一个脚本后,通过创建一个简单的“Hello, World!”来测试它。用于验证一切正常的 Python 文件。通过在文件名后添加命令行参数(例如 python script.py arg1 arg2)来试验命令行参数,以动态传递输入。

探索 Python 开发的高级命令提示符功能,例如使用 pip 通过 pip install numpy 安装软件包。考虑使用 venv 学习虚拟环境,以单独管理项目依赖关系并避免冲突。

  当按钮没有响应时如何重置博世洗碗机