我有具有功能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) –