简体   繁体   English

function的code object使用Python exec如何获取返回值?

[英]How do I get the return value when using Python exec on the code object of a function?

For testing purposes I want to directly execute a function defined inside of another function.出于测试目的,我想直接执行在另一个 function 内部定义的 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.我可以通过父 function 的代码(func_code)获取子 function 的代码 object,但是当我执行它时,我没有返回值。

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:是的,您需要在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和用户定义的输入时要小心。

A few years later, but the following snippet helped me:几年后,但以下片段帮助了我:

the_code = '''
a = 1
b = 2
return_me = a + b
'''

loc = {}
exec(the_code, globals(), loc)
return_workaround = loc['return_me']
print(return_workaround)  # 3

exec() doesn't return anything itself, but you can pass a dict which has all the local variables stored in it after execution. exec()本身不返回任何内容,但您可以传递一个dict ,其中在执行后存储了所有局部变量。 By accessing it you have a something like a return.通过访问它,您可以获得类似回报的东西

I hope it helps someone.我希望它可以帮助某人。

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 never allow any user inputs for the input of this function in there, as it poses an extreme security risk.毋庸置疑,您永远不应该允许任何用户输入用于此功能的输入,因为它会带来极大的安全风险。

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 )中的函数构造函数。

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.因为我只会把它作为最后的手段。

This doesn't get the return value per say, but you can provide an empty dictionary when calling exec to retrieve any variables defined in the code.这不会得到每个说的返回值,但是在调用exec以检索代码中定义的任何变量时,您可以提供一个空字典。

# Python 3
ex_locals = {}
exec("a = 'Hello world!'", None, ex_locals)
print(ex_locals['a'])
# Output: Hello world!

From the Python 3 documentation on exec :来自exec 上Python 3 文档

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted.默认 locals 的行为如下面的函数locals()所述:不应尝试修改默认 locals 字典。 Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.如果您需要在函数exec()返回后查看代码对局部变量的影响,请传递一个显式局部变量字典。

For more information, see How does exec work with locals?有关更多信息,请参阅exec 如何与本地人一起工作?

Here's a solution with a simple code:这是一个带有简单代码的解决方案:

# -*- coding: utf-8 -*-
import math

x = [0]
exec("x[0] = 3*2")
print(x[0]) # 6

Since Python 3.7, dictionary are ordered.从 Python 3.7 开始,字典是有序的。 So you no longer need to agree on a name, you can just say "last item that got created":因此,您不再需要就名称达成一致,您只需说“最后创建的项目”:

>>> d = {}
>>> exec("def addone(i): return i + 1", d, d)
>>> list(d)
['__builtins__', 'addone']
>>> thefunction = d[list(d)[-1]]
>>> thefunction
<function addone at 0x7fd03123fe50>

使用eval()而不是exec() ,它返回结果

if we need a function that is in a file in another directory, eg如果我们需要一个位于另一个目录中的文件中的函数,例如
we need the function1 in file my_py_file.py我们需要在文件my_py_file.py期函数
located in /home/.../another_directory位于/home/.../another_directory
we can use the following code:我们可以使用以下代码:

def cl_import_function(a_func,py_file,in_Dir): def cl_import_function(a_func,py_file,in_Dir):
... import sys ... 导入系统
... sys.path.insert(0, in_Dir) ... sys.path.insert(0, in_Dir)
... ax='from %s import %s'%(py_file,a_func) ... ax='from %s import %s'%(py_file,a_func)
... loc={} ... loc={}
... exec(ax, globals(), loc) ... exec(ax, globals(), loc)
... getFx = loc[afunc] ... getFx = loc[afunc]
... return getFx ...返回getFx

test = cl_import_function('function1',r'my_py_file',r'/home/.../another_directory/') test = cl_import_function('function1',r'my_py_file',r'/home/.../another_directory/')

test()测试()
(a simple way for newbies...) (新手的简单方法...)

program = 'a = 5\nb=10\nprint("Sum =", a + b)'

program = exec(program)

print(program)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何让这个 python 函数返回一个值? - how do i get this python function to return a value? 将 postgresql 与 python 一起使用时,如何返回作为参数放入搜索函数的数据值的所有行值 - How do I return all row values of a data value I put as an argument into a search function when using postgresql with python 如何获取exec的返回值? - How to get return value of exec? 如何获得在另一个函数中调用的函数以返回值? 蟒蛇 - How do I get a function that is called within another function to return a value? PYTHON 如何在 Python 中获取这个华氏到摄氏代码以返回值而不是公式? - How do I get this Fahrenheit to Celsius Code in Python to return a value instead of the formula? 如何在使用返回函数的同时在 python 中获得一个定义的函数来循环? - How do I get a defined function in python to loop whilst using the return function? 在Python中,当执行`if`语句时,如何从函数返回值? - In Python, how do I return a value from a function when an `if` statement is executed? 如何使用Python创建一个函数,该函数将在数据表中的每一行的字典中返回一个值? - How do I create a function that will return a value in a dictionary for each row within a data sheet using Python? 如何从 Python 中的异步函数访问返回值? - How do I access the return value from an async function in Python? 如何使用 exec Python 从 txt 文件中获取 function 值 - How to get function value from txt file with exec Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM