Python 从包中的父目录导入模块

Python 从包中的父目录导入模块,python,python-3.x,python-import,Python,Python 3.x,Python Import,我提到了几条线索和文章,包括: 但并没有达到预期的效果 假设我有一个名为“helloworld”的目录: 这是say_hello.py: def hello_world(): print("Hello World!") if __name__ == "__main__": hello_world() from .. import say_hello say_hello.hello_world() 这是import_hello.py: def hello_world

我提到了几条线索和文章,包括:

但并没有达到预期的效果

假设我有一个名为“helloworld”的目录:

这是say_hello.py:

def hello_world():
    print("Hello World!")
if __name__ == "__main__":
    hello_world()
from .. import say_hello
say_hello.hello_world()
这是import_hello.py:

def hello_world():
    print("Hello World!")
if __name__ == "__main__":
    hello_world()
from .. import say_hello
say_hello.hello_world()
我希望在调用
python/path/to/import\u hello.py时导入
say_hello
模块,而不使用
sys
模块

但是,现在当我执行
python/path/to/import\u hello.py
时,它将返回
ValueError:尝试在顶级包之外进行相对导入,我不知道它为什么不工作

即使这样也不行:

from helloworld import say_hello
say_hello.hello_world()

它将给我
ModuleNotFoundError:没有名为“helloworld”的模块

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

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

希望能有帮助

您不能在这样的包中间运行脚本。当您这样做时,您不是在运行
helloworld.other\u hello.import\u hello
基于
/path/to/helloworldsparent/
,而是在运行
\uu main\uuuu
基于
/path/to/helloworldsparent/helloworld/other\u helloworld>。因此,它没有父包作为
导入


您可以使用
-m
运行模块:

$ python -m helloworld.another_hello.import_hello
…假设
helloworld
的目录位于
sys.path
(例如,因为您已将其安装到
网站包中,或者因为您当前的工作目录是其父目录,或者因为您已设置了
PYTHONPATH


但是一个更干净的解决方案通常是不使用深层模块,而是在顶层编写如下所示的“入口点”脚本:

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

如果您使用的是
setuptools
(对于任何复杂到需要两个级别的软件包,您确实应该这样做),您可以让它在安装时自动创建入口点脚本(或者在开发过程中在
--inplace
时)。请参阅文档中的内容(但您可能还需要阅读其他章节才能了解整个内容;文档非常大且复杂)。

错误非常明显。顶级包没有父文件夹。@Code Peedient我以为我在指定import_hello.py所在的父文件夹。在这种情况下,父文件夹应该是helloworld,不是吗?可能是“谢谢”的副本。但我不太清楚在使用
setuptools
时“不使用深层模块”是什么意思。这是否意味着我可以将import_hello.py保留为现在的状态,即从。。请说声你好;say_hello.hello_world()
?@ytu从…导入
行的
将起作用,但您通常希望将顶级代码(即
say_hello.hello_world()
)移动到一个函数中,该函数可由某人在导入helloworld后调用。另一个
,而不是让它在流程中第一次执行导入操作时运行。换句话说,您希望在包中包含模块,而不是脚本。我感谢您的帮助。然而,我一直未能在
import\u hello
中导入模块,并且在setup.py的入口点中使用控制台脚本创建的命令获取
ModuleNotFoundError
。。。