从包中的父目录导入模块

Import a module from the parent directory within packages

我参考了几个话题和文章,包括:

却得不到想要的结果

假设我有一个名为 "helloworld":

的目录
helloworld
|--__init__.py
|--say_hello.py
|--another_hello
   |--__init__.py
   |--import_hello.py

这是say_hello.py:

def hello_world():
    print("Hello World!")
if __name__ == "__main__":
    hello_world()

这是import_hello.py:

from .. import say_hello
say_hello.hello_world()

我希望在我调用 python /path/to/import_hello.py 的任何地方 导入 say_hello 模块而不使用 sys 模块 .

但是,现在当我执行 python /path/to/import_hello.py 时,它会 return ValueError: attempted relative import beyond top-level package,我不知道为什么它不起作用。

即使这样也行不通:

from helloworld import say_hello
say_hello.hello_world()

它会给我 ModuleNotFoundError: No module named 'helloworld'.

我觉得你可以先尝试将父路径添加到系统路径,然后尝试使用导入。

from sys import path as pylib
import os
pylib += os.path.abspath('..')
from helloworld import say_hello

希望对您有所帮助!!

您不能 运行 像那样从包中间创建脚本。当你这样做时,你不是 运行宁 helloworld.another_hello.import_hello 基于 /path/to/helloworldsparent/,你是 运行宁 __main__ 基于 /path/to/helloworldsparent/helloworld/another_hello.因此,它没有 import 作为 ...

的父包

您可以 运行 模块 -m:

$ python -m helloworld.another_hello.import_hello

…假设 helloworld 的目录在您的 sys.path 上(例如,因为您已将它安装到 site-packages,或者因为您当前的工作目录是它的父目录,或者因为你设置了 PYTHONPATH).


但更简洁的解决方案通常是单独保留深层模块并在顶层编写 "entry point" 脚本,如下所示:

import helloworld.another_hello.import_hello
helloworld.another_hello.import_hello.main()

如果您正在使用 setuptools(并且您确实应该使用任何复杂到需要两层包的东西),您可以让它在安装时自动创建入口点脚本(或在 --inplace 时间,开发期间)。请参阅文档中的 Automatic Script Creation(但您可能还需要阅读其他部分才能了解整个想法;文档非常庞大且复杂)。