如何在函数的代码对象上使用Python exec时获得返回值? [英] How do I get the return value when using Python exec on the code object of a function?
问题描述
为了测试的目的,我想直接执行另一个函数中定义的函数。
我可以通过代码获取子函数的代码对象( func_code)的父函数,但是当我执行它时,我没有返回值。
有没有办法从exec'ed代码获取返回值?
是的,您需要在 exec
语句中进行赋值:
>>> def foo():
... return 5
...
>>> exec(a = foo())
>>> a
5
这可能与您的情况无关,因为它被用于受控测试,但要小心使用 exec
和用户定义的输入。
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.
Is there a way to get the return value from the exec'ed code?
Yes, you need to have the assignment within the exec
statement:
>>> 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.
这篇关于如何在函数的代码对象上使用Python exec时获得返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!