我正在尝试使用 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",
"type": "python",
"request": "launch",
"module": "main"
}
]
}
我敢肯定,我缺少一个简单的设置,但我无法解决它。
备注
"env": {"PYTHONPATH": "${workspaceFolder}"}
至 launch.json
,但这没有任何好处。 ${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.
最佳答案
看看 here
基本上,你想做的是cd /path/to/sandbox
然后 export PYTHONPATH=$(pwd)
现在你在 python-path 中有你的应用程序的根目录。
你只是在这个层面上对待一切。from app.main import MyClass
<- 正确,应该可以工作!
关于python - VSCode : How to import a module from my code path to another file in the same path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687714/