我使用python并从函数调用inspect.getsource(func)中检索另一段代码。
我想要执行代码并获得函数的返回值。
下面是我到目前为止掌握的代码:
def f():
a = 1
v = 2
return 1
import inspect
st = inspect.getsource(f)
b = exec(st)
print(b)但是目前我看到了下面显示的输出。
无
我在这里错过了什么?我希望执行这个函数并返回它应该提供的返回值,就好像我要调用这个函数一样。
欢迎您的提示和建议。
发布于 2020-02-04 17:56:59
exec什么也不回。相反,您可以向它分配如下内容:
def f():
a = 1
v = 2
return 1
import inspect
st = inspect.getsource(f) + '\nret=f()'
exec(st)
print(ret) # prints 1这是另一种选择,但很难看.
In [65]: def f():
...: a = 1
...: v = 2
...: return 1
...:
In [66]: def my_exec(func):
...: try:
...: code = inspect.getsource(func)
...: func_name = func.__name__
...: exec('global ret\n{}\nret={}()'.format(code, func_name))
...: global ret
...: return ret
...: except IOError:
...: return None
...:
In [67]: my_exec(f)
Out[67]: 1这将创建一个全局的ret,定义该函数,然后运行该函数,将返回分配给ret。最后,它返回任何ret包含的内容。通过定义自己的exec函数,您将对前后发生的事情有更多的控制。
https://stackoverflow.com/questions/60062907
复制相似问题