我有具有功能hello()
是否可以将模块注入导入模块的全局变量?
hello.py
文件hello.py
:
def hello():
print "hello world"
我还有一个文件test.py
其中进口hello
,并调用函数。
test.py
:
from hello import *
def run():
hello()
if __name__ == '__main__':
run()
如果我运行test.py
通过蟒蛇,它按预期工作:
$ python test.py
hello world
但是现在,我编辑test.py
,并除去import语句:
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's
范围内。
$ 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
问:
- 是否有可能注入
hello()
成从run.py
,test.py's
范围,而无需run.py
进口hello.py
?
我很高兴使用低级功能,如imp
模块,如果这是必需的。
这是可能的,但隐藏你的依赖从来就不是一个好主意。 – wim
@wim现在离开这是个好主意还是不行,如果可能的话,请分享一下。 –
@wim关于为什么我在寻找这个上下文,请参见[这个问题](http://stackoverflow.com/questions/41004393/boostpython-expose-ac-class-to-a-python-script-embedded -in-ac-app) –