python3 from .a import b 使用 __import__() 函数如何写?


如题所写 python3 中 from .a import b 语句如何使用 __import__() 内置函数写呢?

已知下面这两个path的导入结果是一致的:


 from os import path
path = getattr(__import__("os"), "path")

那目前有这样的目录结构:


 run.py
app/__init__.py
app/index.py
app/ins.py

run.py:
from app import root
root()

app/__init__.py:
from .ins import ins
from .index import root

app/index.py:
from . import ins
def root():
    print(ins)

app/ins.py
ins = "test func"

__init__.py 中使用 from .index import root 是可以正常导入的,那如何将这个 from import 语句替换为 使用 __import__() 函数来写呢?(from 的时候 是从 .index 里面导入的,请不要忘记这个点)

python python3.x import

超级比例看 9 years, 11 months ago

类似这样吗?


 app/__init__.py:
path = getattr(__import__("sys"), "path")
path.append("app")

root = getattr(__import__("index"), "root")
ins = getattr(__import__("ins"), "ins")

app/index.py:
ins = getattr(__import__("ins"), "ins")

def root():
    print(ins)

path.append("app") 还得改成绝对路径。不知道为什么不直接使用import。

净火的神子 answered 9 years, 11 months ago

Your Answer