1

我有一个这样的文件夹

/test_mod
    __init__.py
    A.py
    test1.py
    /sub_mod
        __init__.py
        B.py
        test2.py

我想使用亲戚进口test1test2喜欢这样

#test1.py
from . import A
from .sub_mod import B
...

#test2.py
from .. import A
from . import B
...

当我开发test1或者test2我希望这些导入在我处于空闲状态时工作,也就是说,如果我F5在工作时按下test2每个工作都很好,因为例如我不想这样做python -m test_mod.sub_mod.test2

我已经检查了这个 python-relative-imports-for-the-billionth-time

看着那个,我试过这个:

if __name__ == "__main__" and not __package__:
    __package__ = "test_mod.sub_mod"
from .. import A
from . import B

但这没有用,它给出了这个错误:

SystemError: Parent module 'test_mod.sub_mod' not loaded, cannot perform relative import
4

1 回答 1

0

最后我找到了这个解决方案

#relative_import_helper.py
import sys, os, importlib

def relative_import_helper(path,nivel=1,verbose=False): 
    namepack = os.path.dirname(path)
    packs = []
    for _ in range(nivel):
        temp = os.path.basename(namepack)
        if temp:
            packs.append( temp )
            namepack = os.path.dirname(namepack)
        else:
            break
    pack = ".".join(reversed(packs))
    sys.path.append(namepack)
    importlib.import_module(pack)
    return pack

我用作为

#test2.py
if __name__ == "__main__" and not __package__:
    print("idle trick")
    from relative_import_helper import relative_import_helper
    __package__ = relative_import_helper(__file__,2)

from .. import A
...

然后我可以在 IDLE 工作时使用亲属导入。

于 2016-03-14T21:35:09.360 回答