我正在尝试从另一个 python 文件中导入变量。
a.py
- 待进口
text="Hello, world"
print("imported")
b.py
- 有效,但我不能有静态名称a
from a import *
print(text)
c.py
- 不行
import importlib
X = "a"
try:
text = ""
i = importlib.import_module(X)
print(i)
print(text)
except ImportError as err:
print('Error:', err)
try:
text = ""
i = importlib.__import__(X , globals=True, locals=True, fromlist=[], level=0)
print(i)
print(text)
except ImportError as err:
print('Error:', err)
try:
text = ""
i = importlib.__import__(X , globals=True, locals=True, fromlist=[text], level=0)
print(i)
print(text)
except ImportError as err:
print('Error:', err)
输出是:
imported
<module 'a' from '/tmp/a.py'>
<module 'a' from '/tmp/a.py'>
<module 'a' from '/tmp/a.py'>
但text
变量不起作用。
d.py
- 不行
X = "a"
from X import *
print(text)
可以importlib
用作from MODULE import *
吗?