NameError 在 python 中使用 execfile

2022-01-14 00:00:00 python class namespaces scope

问题描述

我的应用程序有一个使用 execfile 动态执行 python 脚本的按钮.如果我在脚本中定义一个函数(例如.spam())并尝试在另一个函数中使用该函数(例如.eggs()),我会收到此错误:

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() 中调用 spam() 函数的正确方法是什么?

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()

另外,我似乎无法从脚本中的主应用程序执行方法.即

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()

错误是:

NameError: name 'bleh' is not defined

从 my2ndscript.py 调用 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()

但这将创建 mainprogram 的第二个实例.或者,更好的是:

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() 以防脚本在这些点击之间发生变化)?

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()

相关文章