2

给定以下软件包:

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

这很糟糕吗?有没有更好的办法?

4

1 回答 1

1

这肯定会成为未来的维护难题。不仅仅是条件导入......更多的是你必须进行条件导入的原因,即作为主脚本运行导致testpackage/testmod2.py一个条目sys.path./testpackage而不是.,这使得 testpackage作为一个包存在离开。

相反,我建议通过运行 testmod2 python -m testpackage.testmod2,并从外部进行testpackagetestpackage.testmod2仍将显示为__main__,但条件导入将始终有效,因为testpackage将始终是一个包。

问题-m是它需要Python 2.5 或更新版本

于 2011-08-25T03:25:13.597 回答