Skip to main content
 首页 » 编程设计

python之如何在 Windows 10 中配置 Visual Studio Code 以忽略 shebangs 并使用 Python 解释器路径

2024年12月31日15开发

我有一个旨在在 Linux 中运行的 Python 项目:

#!/usr/bin/env python3 
def hello(a: str): 
    print(f"bonjour {a}") 
 
hello("SO") 

当我在 Windows 上使用 Visual Studio Code 编辑这段代码并运行它时,我得到了

[Running] /usr/bin/env python3 "d:\Seafile\dev\dev-perso\domotiqueNG\services\dispatcher\hello.py" 
The system cannot find the path specified. 

如果 Visual Studio Code 打算实际使用 shebang,则错误是可以理解的:env 和 python3 都不存在。

我应该如何配置 Visual Studio Code,以便它不考虑 shebang,而是使用 C:\Python36\python.exe 可执行文件?


我在设置中找到 Python: Python Path 并将其设置为我的可执行文件,但在存在 shebang 的情况下,shebang 优先

我删除了 shebang 以尝试该版本(这不是解决方案,我需要将 shebang 保留在那里)并且有趣的是我得到了:

[Running] python -u "d:\Seafile\dev\dev-perso\domotiqueNG\services\dispatcher\hello.py" 
  File "d:\Seafile\dev\dev-perso\domotiqueNG\services\dispatcher\hello.py", line 2 
    def hello(a: str): 
               ^ 
SyntaxError: invalid syntax 

这很奇怪,因为它似乎暗示编译器无法识别 Python 3.6 语法,而 Python 3.6 是路径中的语法(计算机上隐藏了另外两个 Python 2 可执行文件,甚至不在路径中) .

Visual Studio Code 建议使用 3.6:

所以我怀疑在某处可以调整 Python 可执行路径的设置。

请您参考如下方法:

舍邦

是否使用shebang可以在设置中配置:搜索shebang,然后搜索Code-runner: Respect Shebang

Python版本

当通过 CtrlF5 运行代码时,使用了正确的解释器。

当通过 AltCtrlN (Run Code) 运行时,使用了错误的。

我检查过

import sys 
print(sys.executable) 

并且出于某种原因,展示了 Platform.io 解释器。我不知道它是如何在 Run Code 下结束的,但禁用 Platform.io 有所帮助。 AltCtrlN 和 CtrlF5 现在都使用正确的解释器。

我仍然不知道为什么两种启动脚本的方式使用不同的解释器,但至少现在问题已经解决了。