VS Code无法识别Python,创建虚拟环境遇CommandNotFoundException错误
问题重现
PS C:\Users\dell\Documents\Programming> python -m venv C:\Users\dell\Documents\Programming\venv
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
python -m venv C:\Users\dell\Documents\Programming\venv
CategoryInfo : ObjectNotFound: (python:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundExceptionPS C:\Users\dell\Documents\Programming> python3 -m venv C:\Users\dell\Documents\Programming\venv
python3 : The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundExceptionPS C:\Users\dell\Documents\Programming> python3 -m venv C:\Users\dell\Documents\Programming\venv
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
已关闭App Execution Aliases中的python和python3选项,但问题仍存在。
解决步骤
确认Python安装完整性
找到Python的安装目录(默认路径通常是C:\Users\dell\AppData\Local\Programs\Python\PythonXX,XX为具体版本号,比如311),检查目录下是否存在python.exe,双击该文件验证能否正常启动Python解释器。添加Python路径到系统环境变量PATH
- 右键「此电脑」→「属性」→「高级系统设置」→「环境变量」
- 在「系统变量」区域找到
Path变量,点击「编辑」 - 添加两个路径:
- Python安装根目录(例如
C:\Users\dell\AppData\Local\Programs\Python\Python311) - Python的Scripts子目录(例如
C:\Users\dell\AppData\Local\Programs\Python\Python311\Scripts)
- Python安装根目录(例如
- 保存所有设置后,必须重启所有已打开的PowerShell和VS Code窗口,环境变量才会生效。
验证Python命令可用性
打开新的PowerShell窗口,输入python --version或py --version,若能正常显示Python版本号,说明环境变量配置成功。临时解决方案:使用绝对路径创建虚拟环境
如果环境变量暂时未生效,直接使用Python可执行文件的绝对路径执行命令:C:\Users\dell\AppData\Local\Programs\Python\Python311\python.exe -m venv C:\Users\dell\Documents\Programming\venv配置VS Code的Python解释器
- 在VS Code中按下
Ctrl+Shift+P打开命令面板 - 输入
Python: Select Interpreter,选择已安装的Python版本 - 重新打开VS Code终端,此时终端会自动关联选中的Python环境,可直接执行
python -m venv命令
- 在VS Code中按下
内容的提问来源于stack exchange,提问作者Ayaz

