在函数的代码对象上使用 Python exec 时如何获取返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23917776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the return value when using Python exec on the code object of a function?
提问by user2433423
For testing purposes I want to directly execute a function defined inside of another function.
出于测试目的,我想直接执行在另一个函数中定义的函数。
I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value.
我可以通过父函数的代码(func_code)到达子函数的代码对象,但是当我执行它时,我没有得到返回值。
Is there a way to get the return value from the exec'ed code?
有没有办法从执行的代码中获取返回值?
回答by wnnmaw
Yes, you need to have the assignment within the exec
statement:
是的,您需要在exec
语句中进行赋值:
>>> def foo():
... return 5
...
>>> exec("a = foo()")
>>> a
5
This probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec
with user defined input.
这可能与您的情况无关,因为它用于受控测试,但在使用exec
用户定义的输入时要小心。
回答by georg
Something like this can work:
这样的事情可以工作:
def outer():
def inner(i):
return i + 10
for f in outer.func_code.co_consts:
if getattr(f, 'co_name', None) == 'inner':
inner = type(outer)(f, globals())
# can also use `types` module for readability:
# inner = types.FunctionType(f, globals())
print inner(42) # 52
The idea is to extract the code object from the inner function and create a new function based on it.
这个想法是从内部函数中提取代码对象并基于它创建一个新函数。
Additional work is required when an inner function can contain free variables. You'll have to extract them as well and pass to the function constructor in the last argument (closure
).
当内部函数可以包含自由变量时,需要额外的工作。您还必须提取它们并传递给最后一个参数 ( closure
) 中的函数构造函数。
回答by devsnd
While this is the ugliest beast ever seen by mankind, this is how you can do it by using a global variable inside your exec call:
虽然这是人类见过的最丑陋的野兽,但您可以通过在 exec 调用中使用全局变量来做到这一点:
def my_exec(code):
exec('global i; i = %s' % code)
global i
return i
This is misusing global variables to get your data across the border.
这是滥用全局变量来跨越边界获取数据。
>>> my_exec('1 + 2')
3
Needless to say that you should neverallow any user inputs for the input of this function in there, as it poses an extreme security risk.
毋庸置疑,您永远不应该允许任何用户输入用于此功能的输入,因为它会带来极大的安全风险。
回答by Menzies
Here's a way to return a value from exec'd code:
这是一种从 exec 代码返回值的方法:
def exec_and_return(expression):
exec(f"""locals()['temp'] = {expression}""")
return locals()['temp']
I'd advise you to give an example of the problem you're trying to solve. Because I would only ever use this as a last resort.
我建议你举一个你试图解决的问题的例子。因为我只会把它作为最后的手段。