繁体   English   中英

将 python 路径添加到 Visual Studio 代码中的模块

[英]add a python path to a module in visual studio code

我在指定 python 路径时遇到困难,该路径包含另一个目录甚至同一项目的文件夹中的模块/包。 当我尝试导入时,出现错误:

ModuleNotFoundError:没有名为“感知”的模块

在 Spyder 中,这只是使用 select 的 UI 来完成,这是 python 将查看的附加 pythonpath,但我无法在 VSC 中这样做。

注意我已尝试在编辑 settings.json 文件和 .env 文件时遵循其他答案,但问题仍然存在。

我唯一的解决方案是在每个脚本中使用 sys.path.append() ,这不是我想要的。

例如,我的 settings.json 文件是:

{

"terminal.integrated.env.osx": {
    "PYTHONPATH": "pathtoprojectfolder"
},
"python.envFile": "${workspaceFolder}/.env",
"jupyter.interactiveWindowMode": "perFile",
"python.terminal.executeInFileDir": true,
"terminal.integrated.inheritEnv": true,
"jupyter.themeMatplotlibPlots": true,
"window.zoomLevel": 2,
"python.condaPath": "path_to_conda_python",
"python.defaultInterpreterPath": "path_to_conda_python",

}

仅适用于 MacOS 的说明。

添加 .env 文件和导航设置 json 文件并不像在 Spyder 中添加额外的 python 路径那么直观和简单。 但是,这在 VSC 上对我有用:

  1. 在项目文件夹中创建一个 .env 文件。
  2. 添加要添加到 PYTHONPATH 的完整路径,如下所示: PYTHONPATH=/Users/../projectFolder:/Users/.../AnotherProjectFolder

** 至关重要的是,您必须在路径之间使用适当的分隔符,在 Mac 上您必须使用 ':',否则将不会添加路径。

  1. go 到代码->首选项->设置并搜索“terminal.integrated.osx”。 点击编辑“settings.json”

  2. 添加到 json 设置

    "python.envFile": "${workspaceFolder}/.env",

例如,您可能有 settings.json 显示以下内容:

{
    "python.envFile": "${workspaceFolder}/.env",
    "jupyter.interactiveWindowMode": "perFile", 
    "python.terminal.executeInFileDir": true,
}

添加路径是一个相当复杂的过程,但我喜欢在 VSC 中运行 Jupyter 笔记本的能力,而 Spyder 在独立安装程序中还没有这种能力。

此页面包含所需的信息: https://code.visualstudio.com/docs/python/environments#_environment-variable-definitions-file

在您的 launch.json 配置文件条目中,指定一个名为“env”的新条目,然后自己设置 PYTHONPATH。

"configurations": [
    {
        "name": "Python",
        "type": "python",
        "stopOnEntry": false,
        "request": "launch",
        "pythonPath": "${config.python.pythonPath}",
        "program": "${file}",
        "cwd": "${workspaceRoot}",
        "debugOptions": [
            "WaitOnAbnormalExit",
            "WaitOnNormalExit",
            "RedirectOutput"
        ],
        "env": {
            "PYTHONPATH": "/path/a:path/b"
        }
    }
]

暂无
暂无

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

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