問題描述
我的應(yīng)用程序有一個(gè)使用 execfile 動態(tài)執(zhí)行 python 腳本的按鈕.如果我在腳本中定義一個(gè)函數(shù)(例如.spam())并嘗試在另一個(gè)函數(shù)中使用該函數(shù)(例如.eggs()),我會收到此錯(cuò)誤:
My application has a button to execute a python script dynamically using execfile. If I define a function inside the script (eg. spam()) and try to use that function inside another function (eg. eggs()), I get this error:
NameError: global name 'spam' is not defined
從 eggs() 中調(diào)用 spam() 函數(shù)的正確方法是什么?
What is the correct way to call the spam() function from within eggs()?
#mainprogram.py
class mainprogram():
def runme(self):
execfile("myscript.py")
>>> this = mainprogram()
>>> this.runme()
# myscript.py
def spam():
print "spam"
def eggs():
spam()
eggs()
另外,我似乎無法從腳本中的主應(yīng)用程序執(zhí)行方法.即
Also, I can't seem to be able to execute a method from my main application in the script. i.e.
#mainprogram.py
class mainprogram():
def on_cmdRunScript_mouseClick( self, event ):
execfile("my2ndscript.py")
def bleh():
print "bleh"
#my2ndscript.py
bleh()
錯(cuò)誤是:
NameError: name 'bleh' is not defined
從 my2ndscript.py 調(diào)用 bleh() 的正確方法是什么?
What is the correct way to call bleh() from my2ndscript.py?
編輯:更新第一期
推薦答案
第二種情況你需要import
(不確定是否mainprogram.py"在你的 $PYTHONPATH
)
In the second case you will need import
(not sure whether "mainprogram.py"
is on your $PYTHONPATH
)
#mainprogram.py
class mainprogram:
def runme(self):
execfile("my2ndscript.py")
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
import mainprogram
x = mainprogram.mainprogram()
x.bleh()
但這將創(chuàng)建 mainprogram
的第二個(gè)實(shí)例.或者,更好的是:
but this will create a second instance of mainprogram
. Or, better yet:
#mainprogram.py
class mainprogram:
def runme(self):
execfile("my2ndscript.py", globals={'this': self})
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
this.bleh()
我想 execfile
無論如何都不是解決您問題的正確方法.為什么不使用 import
或 __import__
(以及 reload()
以防腳本在這些點(diǎn)擊之間發(fā)生變化)?
I guess that execfile
is not the right solution for your problem anyway.
Why don't you use import
or __import__
(and reload()
in case the script changes between those clicks)?
#mainprogram.py
import my2ndscript
class mainprogram:
def runme(self):
reload(my2ndscript)
my2ndscript.main(self)
def bleh(self):
print "bleh"
if __name__ == '__main__':
mainprogram().runme()
#my2ndscript.py
def main(program):
program.bleh()
這篇關(guān)于NameError 在 python 中使用 execfile的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!