我已经提到了一些主题和文章,包括:
但无法获得理想的结果。
假设我有一个名为“ 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()
我希望在不使用module的情况下将调用的模块导入say_hello
python /path/to/import_hello.py
sys
。
但是,现在,当我这样做时python /path/to/import_hello.py
,它将返回ValueError: attempted relative import beyond top-level package
,并且我不知道为什么它不起作用。
即使这样也不起作用:
from helloworld import say_hello
say_hello.hello_world()
它会给我的ModuleNotFoundError: No module named 'helloworld'
。
您不能在这样的程序包中间运行脚本。执行此操作时,您不是helloworld.another_hello.import_hello
基于out of/path/to/helloworldsparent/
运行,而是__main__
基于out of运行/path/to/helloworldsparent/helloworld/another_hello
。因此,它没有import
as的父包..
。
您可以使用以下命令运行该模块-m
:
$ python -m helloworld.another_hello.import_hello
…假设helloworld
目录位于您的目录中sys.path
(例如,因为您已将目录安装到中site-packages
,或者因为当前工作目录是其父目录,或者因为您已经建立PYTHONPATH
)。
但是,更干净的解决方案通常是不使用深度模块,而在顶层编写“入口点”脚本,如下所示:
import helloworld.another_hello.import_hello
helloworld.another_hello.import_hello.main()
如果您正在使用setuptools
(确实应该使用足够复杂的东西来需要两个级别的软件包),则可以使其在安装时(或--inplace
在开发过程中)自动创建入口点脚本。请参阅文档中的“自动脚本创建”(但您可能还需要阅读其他部分以了解整个概念;文档非常大且复杂)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句