简体   繁体   English

Visual Studio Code Python路径设置不正确

[英]Visual Studio Code Python path set incorrectly

I am using Visual Studio Code and would like to use the integrated terminal to run or debug my code. 我正在使用Visual Studio Code,并且想使用集成终端来运行或调试我的代码。

I have a python file in a scripts subdirectory. 我在scripts子目录中有一个python文件。 Everything runs correctly if I move it up one level to the project root directory. 如果我将其上移到项目根目录上一级,则一切运行正常。 However, in the scripts subdirectory I cannot import the Python modules I have created. 但是,在scripts子目录中,我无法导入已创建的Python模块。

If I add this to the top of my file it will work correctly: 如果将其添加到文件顶部,它将可以正常工作:

import sys
import os

sys.path.insert(0, os.getcwd())
print(sys.path)

If I don't do that insert statement I get a ModuleNotFoundError exception. 如果我不执行该插入语句, ModuleNotFoundError收到ModuleNotFoundError异常。

This is my debug configuration: 这是我的调试配置:

{
    "name": "Python: Current File (Integrated Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal"
}

What do I do to make sure the Python path always includes the project root directory, regardless of where the script file is located? 无论脚本文件位于何处,如何确保Python路径始终包含项目根目录?

I got it to work by setting an environment variable in the launch configuration. 我通过在启动配置中设置环境变量来使其工作。

    {
        "name": "Python: Current File (Integrated Terminal)",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
        "env": {"PYTHONPATH": "${workspaceFolder}"}
    }

The last line did the trick. 最后一行起到了作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM