我有一个文件hello.py
,其中包含一个名为hello()
的函数。
hello.py
:
def hello():
print "hello world"
我有另一个文件test.py
,它导入了hello
并调用了函数。
test.py
:
from hello import *
def run():
hello()
if __name__ == '__main__':
run()
如果我通过Python运行test.py,它会按预期工作:
$ python test.py
hello world
现在,我要编辑
test.py
,并且删除导入语句:
test.py
:
def run():
hello() # hello is obviously not in scope here
if __name__ == '__main__':
run()
我介绍一个第三个文件,run.py
,它同时导入了hello.py
和test.py
run.py
:
from hello import *
from test import *
if __name__ == '__main__':
run()
自然地,这是无法工作的,因为
hello()
不在test.py
的范围内。$ python run.py
Traceback (most recent call last):
File "run.py", line 5, in <module>
run()
File "test.py", line 4, in run
hello()
NameError: global name 'hello' is not defined
问题:
- 是否可以在不让
run.py
导入hello.py
的情况下,从run.py
将hello()
注入到test.py
的作用域中?
如果需要,我可以使用较低级别的功能,例如imp
模块。
from hello import *
确实在导入hello.py
。只是它没有在run.py
的全局命名空间中绑定一个模块名称而已。接着使用import hello
将不涉及第二次导入,它只会从缓存中提取已经导入的模块。 - ShadowRanger