首页 > 解决方案 > vscode 找不到我的自定义 python 包

问题描述

我是 VS Code 在 Windows 上进行 python 开发的新手,我的 pylint 找不到包。这是我的项目目录结构。

workspace/    <- This is VS Code workspace (E:\workspace)
  .vscode/
    launch.json
    settings.json    
  project1/
    mypackge/
      __init__.py          <- In here, I wrote: `import mypackage.first_sub_pkg`
      first_sub_pkg/
        __init__.py        <- In here, I wrote: `from .second_sub_pkg.mymodule import MyClass`
        second_sub_pkg/
          __init__.py      <- In here, I wrote: `from .mymodule import MyClass`
          mymodule.py    <- This module has class: `MyClass`
    test_script/
      mytest.py
  project2/
  etc.../

我编写了 mytest.py 脚本代码,例如:

from mypackge.first_sub_package import MyClass

我使用 C:/Anaconda3/python.exe 作为 python 解释器

当我单击 VS Code 右上角的按钮▷(在终端中运行 Python 文件)时,我收到此错误消息

PS E:\workspace> & c:/Anaconda3/python.exe e:/workspace/project1/test_script/mytest.py
Traceback (most recent call last):
  File "e:/workspace/project1/test_script/mytest.py", line 1, in <module>
    from first_sub_pkg.second_sub_pkg import MyClass
ModuleNotFoundError: No module named 'first_sub_pkg'

另外,我添加了 workspace/.vscode/launch.json ,例如:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "pythonPath": "${command:python.interpreterPath}",
            "env": {
                "PYTHONPATH": "${workspaceFolder};E:/workspace/project1"
            }
        }
    ]
}

和 workspace/.vscode/settings.json 像:

{
    "python.autoComplete.extraPaths": [
        "E:/workspace",
        "E:/workspace/project1",
        "E:/workspace/project1/first_sub_pkg",
    ],
    "python.pythonPath": "c:/Anaconda3/python.exe",
    "terminal.integrated.shell.windows": "C:/windows/System32/WindowsPowerShell/v1.0/powershell.exe",
    "python.linter": "pyLint",
    "python.linting.pylintPath": "pylint"
}

我的用户 settings.json 文件是这样的:

{
    "python.autoComplete.extraPaths": [
        "E:/workspace",
        "E:/workspace/project1",
        "E:/workspace/project1/first_sub_pkg",
    ]
}

我已经在 Eclipse + pydev 环境下运行过这个测试脚本,运行没有问题。但不知何故,VSC 无法导入我的模块。

我似乎是系统路径问题,因为当我运行 python 并将 'E:/workspace/project1' 附加到系统路径 ( import sys; sys.path.append('E:/workspace/project1');) 时它运行良好,但我无法找到解决问题的方法。(在 Windows 设置中添加系统变量也不起作用)。

我错过了什么?有人请帮助我。我搜索了2天,但一无所获。

标签: pythonvisual-studio-codevscode-settingspythonpathpythoninterpreter

解决方案


first_sub_pkg与文件不在同一目录中mytest.py。您首先必须向上移动一个级别,project1/然后mypackage/再继续进行其余的导入。所以你做的进口mytest.py应该是这样的:

from ..mypakage.first_sub_pkg.second_sub_pkg.third_sub_pkg.mymodule import MyClass

为什么你有这么多子目录我不知道,但是你的目录结构很快就会变得非常混乱。编码时请牢记python的禅意。


推荐阅读