【发布时间】:2020-11-04 21:20:03
【问题描述】:
我是 Windows 上用于 python 开发的 VS Code 的新手,我的 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 天,但没有找到。
【问题讨论】:
-
从终端运行脚本(就像你目前正在做的那样)应该与 vscode 没有任何关系
-
我找到了我需要的确切解决方案。 stackoverflow.com/questions/53653083/…
标签: python visual-studio-code vscode-settings pythonpath pythoninterpreter