我有一个自动生成的Python代码片段,我想在类实例中exec() 。
简化的代码段如下所示:
prog = """ def func1(): func2() def func2(): pass func1() """ class test(): def run(self): exec(prog) test().run() # results in NameError: name 'func2' is not defined exec(prog) # works虽然在两种情况下都可以调用func1() ,但是当从类中exec()时,找不到func2 。 如果我先运行exec(prog) ,那么即使是test().run()也会成功。 似乎前面的exec调用将func2留在命名空间中的某个位置,以后可以在类中调用它时找到它。
是否有一种简单而干净的方法来调用包含类中几个函数的代码片段?
I have an auto-generated Python code snippet which I'd like to exec() from within a class instance.
A simplified snippet looks like this:
prog = """ def func1(): func2() def func2(): pass func1() """ class test(): def run(self): exec(prog) test().run() # results in NameError: name 'func2' is not defined exec(prog) # worksWhile func1() can be called in both cases, func2 isn't found when exec()'ing from within the class. If I run the exec(prog) first, then even the test().run() succeeds. It seems that the previous exec call left func2 at some place in the namespace where it can later be found when called from within the class.
Is there a simple and clean way to call such a code snippet containing several functions from within a class?
最满意答案
您可以使用exec(prog, globals())来执行全局命名空间中的代码。
You can use exec(prog, globals()) to execute the code in the global namespace.
更多推荐
发布评论