在 VSCode 的 Python 代码中使用绝对导入路径

发布于 2025-01-14 13:28:22 字数 432 浏览 4 评论 0原文

工作区文件夹是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绳情 2025-01-21 13:28:22

您可以通过以下方式获取 PYTHONPATH

import sys
from pprint import pprint
pprint(sys.path)

:执行的python脚本的文件夹路径将自动添加到PYTHONPATH(引用)。

在程序启动时初始化,此列表的第一项,
path[0],是包含用于的脚本的目录
调用Python解释器。如果脚本目录不是
可用(例如,如果解释器被交互调用或者如果
脚本是从标准输入读取的),path[0] 是空字符串,
它指示 Python 首先在当前目录中搜索模块。
请注意,脚本目录被插入到条目之前
作为 PYTHONPATH 的结果插入。

myapp 文件夹父文件夹路径PYTHONPATH中不存在,因此myapp 不会被视为模块,因此 from myapp.module import math 将不起作用。

myapp的文件夹路径在PYTHONPATH中,因此可以搜索module,然后from module import math就可以了。

You can get PYTHONPATH through:

import sys
from pprint import pprint
pprint(sys.path)

The parent folder path of executed python script will be added to PYTHONPATH automatically(refer).

As initialized upon program startup, the first item of this list,
path[0], is the directory containing the script that was used to
invoke the Python interpreter. If the script directory is not
available (e.g. if the interpreter is invoked interactively or if the
script is read from standard input), path[0] is the empty string,
which directs Python to search modules in the current directory first.
Notice that the script directory is inserted before the entries
inserted as a result of PYTHONPATH.

The parent folder path of myapp folder does not exist in the PYTHONPATH, so myapp will not be treated as a module, so from myapp.module import math will not work.

While folder path of myapp in the PYTHONPATH, so module can be searched, then from module import math will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文