我正在尝试使用VSCode调试python应用程序。但是我无法正确配置我的环境。尝试将类从我的源路径中的一个文件夹导入到另一个文件夹,将显示以下消息:
Traceback (most recent call last):
File "/Users/mb/library/source/sandbox/lib/lib.py",line 1,in <module>
from app.main import MyClass
ModuleNotFoundError: No module named 'app'
我创建了一个简单的应用来展示该问题。我的源路径如下:
sandbox
+-- .vscode
--- launch.json
+-- app
--- __init__.py
--- main.py
+-- lib
-- lib.py
# main.py
class MyClass:
def __init__(self):
print('Creating object...')
def print_message(self,message):
print(message)
# lib.py
from app.main import MyClass
myclass = MyClass()
myclass.print_message('hello,world!')
尝试使用默认配置运行lib.py
来运行当前文件,我得到上面的错误消息。
此外,我创建了一个.vscode/launch.json
来设置工作目录,但无济于事。这是我的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","cwd": "${workspaceFolder}"
},{
"name": "Python: Module","module": "main"
}
]
}
我敢肯定,我错过了一个简单的设置,但是我不能把手放在上面。
注意
- 使用的解释器是:Python 3.7.5 64位
- 上面的代码在PyCharm中工作正常。
- 在阅读了VSCode文档之后,我在
"env": {"PYTHONPATH": "${workspaceFolder}"}
上添加了launch.json
,但这没有任何好处。 - 我还创建了一个VSCode task 来回显
${workspaceFolder}
变量,并且从路径中剥离了所有\
的输出,就好像它们没有被转义一样。 这是.vscode/tasks.json
中的任务:
{
"version": "2.0.0","tasks": [
{
"label": "workspaceFolder","type": "shell","command": "echo ${workspaceFolder}"
}
]
}
这是从中获得的输出:
> Executing task: echo C:\Users\mb\library\source\sandbox <
C:Usersmblibrarysourcesandbox
Terminal will be reused by tasks,press any key to close it.