如何使主程序包或脚本与子模块同时成为包

2024-06-07 00:16:16 发布

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

我有这样的结构:

app.py
sub/
    __init__.py
    lib.py
    utils.py

app.py中,我想做这样的事情:

from sub.lib import some_func

lib.py中,我希望能够导入utils.py。你知道吗

我还希望可以直接将lib.py作为脚本执行

问题是,如果我将lib.py作为脚本启动,它将不是一个包,因此,它不能使用相对导入,因此from .utils import some_util_func之类的东西将不起作用。但是,如果我将lib.py作为sub包的一部分导入,则只有相对导入可以工作。你知道吗

我该怎么解决这个问题?(以一种简单的方式。例如,不创建另一个小包装器脚本来调用lib.py。)

例如,如果有一种方法将__main__模块标记为一个包,它将解决这个问题。但是怎么做呢?这可能吗?例如,通过定义__path__左右?你知道吗


Tags: frompyimport脚本appinitlibutil
2条回答

启动程序时可以设置PYTHONPATH环境变量。你知道吗

只需从lib目录键入:

PYTHNONPATH="path/to/root/directory" python lib.py

好吧,事实上,我最后的评论真的很有效。如果我在lib.py的开头加上这个,似乎可以:

import os

if __name__ == '__main__':
    __path__ = [os.path.dirname(os.path.abspath(__file__))]

(关于__path__,参见例如here。)


此外,在PEP 366中提到:

When the main module is specified by its filename, then the __package__ attribute will be set to None. To allow relative imports when the module is executed directly, boilerplate similar to the following would be needed before the first relative import statement:

if __name__ == "__main__" and __package__ is None:
    __package__ = "expected.package.name"

我还没试过呢。你知道吗

相关问题 更多 >