如何在python3.6中使用绝对和相对导入?

2024-05-20 07:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“slingshot”的python项目/库,其目录结构如下:

slingshot/
    __init__.py
    __main__.py
    build.py
    deploy.py
    util/
        __init__.py
        prepare_env.py
        cdn_api.py

__main__.py我想从util/prepare_env.py导入函数。在

我想确保util引用我项目中的util,而不是其他可能安装在某处的{}库。在

我尝试了from .util import prepare_env,但是我得到了一个错误。在

from util import prepare_env似乎可以工作,但不能解决“util”的模糊性。在

我做错什么了?在


__main__.py如下:

^{pr2}$

当我输入python3 ./slingshot时,我得到以下错误:

  File "./slingshot/__main__.py", line 2, in <module>
    from .util import prepare_env
ImportError: attempted relative import with no known parent package

当我输入python3 -m ./slingshot时,我得到以下错误:

/usr/local/opt/python3/bin/python3.6: Relative module names not supported

Tags: 项目frompyimport目录envinitmain
1条回答
网友
1楼 · 发布于 2024-05-20 07:17:00

当您使用-m命令行开关时,包中的__main__.py模块使模块作为脚本运行。该开关使用模块名,而不是路径,因此删除./前缀:

python3 -m slingshot

当前工作目录被添加到模块搜索路径的开始处,因此slingshot首先被找到,无需在这里给出相对路径说明。在

^{} switch documentation

Search sys.path for the named module and execute its contents as the __main__ module.

Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid absolute Python module name[.]

[...]

As with the -c option, the current directory will be added to the start of sys.path.

相关问题 更多 >