给定以下包:
testpackage
__init__.py
testmod.py
testmod2.py
__init__.py的内容
from . import testmod
from . import testmod2
testmod.py的内容
# relative import without conditional logic, breaks when run directly
from . import testmod2
...
if __name__ == '__main__':
# do my module testing here
# this code will never execute since the relative import
# always throws an error when run directly
testmod2.py的内容
if __name__ == 'testpackage.testmod2':
from . import testmod
else:
import testmod
...
if __name__ == '__main__':
# test code here, will execute when the file is run directly
# due to conditional imports
这不好吗?有没有更好的办法?
请您参考如下方法:
那以后肯定会成为维护的头疼问题。不仅仅是条件导入...更多的原因为什么你必须进行条件导入,即运行 testpackage/testmod2.py 作为主脚本导致sys.path 的第一个条目是 ./testpackage 而不是 .,这使得 testpackage 作为一个包 走开。
相反,我建议通过 python -m testpackage.testmod2 运行 testmod2,并从 testpackage 外部进行。 testpackage.testmod2 仍将显示为 __main__,但条件导入将始终有效,因为 testpackage 始终是一个包。
-m 的问题在于它需要 Python 2.5 or newer .
