如何在不执行python -m的情况下使用相对导入? [英] How to use relative import without doing python -m?

查看:226
本文介绍了如何在不执行python -m的情况下使用相对导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件夹

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

我想在 test1 test2 中使用亲戚进口这个

And I want to use relatives imports in test1 and test2 like this

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

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

我开发 test1 test2 我希望那些导入在我进入IDLE时工作,即如果我按 F5 test2 工作时,每次工作都很好,因为我不想做 python -m test_mod.sub_mod.test2

While I develop test1 or test2 I want that those imports to work while I am in the IDLE, that is if I press F5 while working in test2 that every work fine, because I don't want to do python -m test_mod.sub_mod.test2 for instance.

我已经检查了这个
第十亿次进入python-relative-imports

看着那个,我试过了这个:

Looking at that, I tried this:

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

但是这不起作用,它给出了这个错误:

But that didn't work, it gave this error:

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


推荐答案

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

in the end I found this solution

#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工作时使用亲戚导入。

then I can use relatives import while working in the IDLE.

这篇关于如何在不执行python -m的情况下使用相对导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆