我正在构建一个同时使用 Python 和 C 的项目,因此我不使用 Pycharm,而是使用 VS Code 作为我的主要工具。
这是我的简单测试示例,以确保一切正常工作。
测试.py
import sys
#import modules.custom
if __name__ == "__main__":
print(sys.path)
for path in sys.path:
print(path)
而且,我的工作目录结构如下:
-workspace
|-modules
| |-__init__.py
| |-custom.py
|-test
|-test.py
我已经设置了conda环境,配置了VSCode的python解释器的路径,添加了pythonpath等环境变量,现在VS Code本身的F5工作正常,输出如下
/mnt/e/workspace/test
/mnt/e/workspace/
XXXXXXX/lib/python3.9
......(other python paths)
但是目前“code runner”仍然找不到自定义模块,因为code runner打印的路径不包含workspaceFolder。当使用“code runner”运行代码时,输出是
/mnt/e/workspace/test
XXXXXXX/lib/python3.9
......(other python paths)
我觉得学习如何使用代码运行器真的很难:(。我已经做了一些事情来解决这个问题。
代码运行器默认在“输出”窗口中运行python,而不是在“终端”中,并且“输出”窗口似乎无法正确显示打印消息。所以我更改了代码运行器的配置,使其始终在终端中运行。如果这会导致任何问题?
我已经在终端激活了conda环境,所以如上所示,code runner启动的程序可以找到正确的python解释器和python包。但是,我仍然没有找到让代码运行程序识别workspaceFolder目录的方法,因此仍然无法导入自定义模块。
选择解释器、调试功能等对Code Runner扩展没有影响,因为它们都是官方扩展Python带来的设置和功能。 Code Runner 使用
python -u "path\to\name.py"
命令简单直接地执行脚本。
所以你需要先知道你的hcch使用的是哪个python环境,我认为不应该是你为vscde设置的conda环境。您可以使用以下代码来输出解释器路径。
import sys
print(sys.executable)
一旦您知道Code Runner正在使用哪个Python环境,您就可以将
.pth
文件添加到path\to\Python\Lib\site-packages
,然后将workspace
添加到其中。
文件结构: