在 VSCode 的 Python 代码中使用绝对导入路径
工作区文件夹是 myapp
,文件夹结构如下:
myapp/
main.py
__init__.py
module/
__init__.py
math.py
在 main.py
的顶级工作区文件夹中,我想使用绝对路径导入数学包,例如所以:
from myapp.module import math
这会引发错误“没有名为‘myapp’的模块”,并且 pylance 插件也无法找到该包。如果我删除 myapp 前缀,一切都会正常:
from module import math
How do i resolve this in VSCode?
The workspace folder is myapp
and the folder structure is the following:
myapp/
main.py
__init__.py
module/
__init__.py
math.py
In the top level workspace folder in main.py
I would like to import the math package using an absolute path like so:
from myapp.module import math
This throws an error "No module named 'myapp'" and the pylance addon also fails to find the package. Everything works if i remove the myapp prefix:
from module import math
How do i resolve this in VSCode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过以下方式获取 PYTHONPATH
:执行的python脚本的文件夹路径将自动添加到PYTHONPATH(引用)。
myapp 文件夹
的父文件夹路径
在PYTHONPATH
中不存在,因此myapp
不会被视为模块,因此from myapp.module import math
将不起作用。而
myapp
的文件夹路径在PYTHONPATH中,因此可以搜索module
,然后from module import math
就可以了。You can get PYTHONPATH through:
The parent folder path of executed python script will be added to PYTHONPATH automatically(refer).
The
parent folder path
ofmyapp folder
does not exist in thePYTHONPATH
, somyapp
will not be treated as a module, sofrom myapp.module import math
will not work.While folder path of
myapp
in the PYTHONPATH, somodule
can be searched, thenfrom module import math
will work.