python 模块和导入

python module and imports

如果这是我的目录树

temp
├── __init__.py
└── __main__.py

0 directories, 2 files

我在 __init__.py__main__.py

中有以下代码

__init__.py

"""Initializes the module"""

CONSTANT = 1
sys.exit("what is happening here")

__main__.py

# from . import CONSTANT
# from temp import CONSTANT
if __name__ == "__main__":

    print "This should never run"

这里有两个问题,我正在努力解决

On 运行 python .temp 目录中我得到了输出 This should never run,模块不应该先用 __init__.py 文件初始化导致中止吗?

其次,我如何在 python 模块中进行导入?我上面提到的两个选项都不起作用。我既不能在上面的代码中执行 from . import CONSTANT 也不能执行 from temp import CONSTANT 。做相对进口的正确方法是什么?

我是 运行 在 Python 2.7.5 上,如果之前有人问过这个问题,我深表歉意。

您应该从 temp 目录中 运行 安装它。如果 someDir 包含您的 temp 目录,则:

someDir $ python -m temp   #someDir/temp/__init__.py is your file.

On running python . in the temp directory I get the output This should never run, shouldn't the module be initialized first with the init.py file resulting in the abort?

如果你从外面运行它,__init__.py将被调用。 sys.exit 也会被调用。


Second how do I go about doing imports in python modules? Neither of the two options I have mentioned above works. I can neither do from . import CONSTANT nor from temp import CONSTANT in the code above. What is the right way to do relative imports?

你做得很好。只需在 __init__.py 文件中导入 sys。并修复 CONSTANT.

的拼写

Also why do I need the -m flag? Isn't it ok to just do python temp from the parent directory of temp?

您需要 -m 标志来表明您正在使用包。如果你不使用它,你将无法进行相对导入。

你在运行宁里面temp;这不被视为一个包, __init__.py 未加载。仅当当前目录的 parent 在模块加载路径上并且您显式加载 temp 作为模块时,才会加载 __init__.py

因为 temp 不是包 你不能在这里使用相对导入。相反,目录中的每个 Python 文件本身都被视为顶级模块。

你必须移动到 temp 目录的父目录,然后 运行:

python -m temp

为了 Python 将 temp 作为一个包导入,然后 运行 该包中的 __main__ 模块。

当您告诉 Python 到 运行 目录时,Python 不会将该目录视为包 。相反,Python adds that directory to sys.path and runs its __main__.py__init__.py 不执行,相对导入不会将目录视为包。

如果你想 运行 一个包的 __main__.py 并将其视为包的一部分,执行 __init__.py 和所有,转到包含包的目录和 运行

python -m packagename