Mr.*_* B. 20
几年后,但以下片段帮助了我:
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
Run Code Online (Sandbox Code Playgroud)
exec()本身不返回任何内容,但您可以传递 a dict,其中在执行后存储了所有局部变量。通过访问它,您可以获得类似回报的东西。
我希望它可以帮助某人。
wnn*_*maw 18
是的,您需要在exec声明中进行分配:
>>> def foo():
... return 5
...
>>> exec("a = foo()")
>>> a
5
Run Code Online (Sandbox Code Playgroud)
这可能与您的案例无关,因为它用于受控测试,但要小心使用exec用户定义的输入.
dev*_*snd 10
虽然这是人类见过的最丑陋的野兽,但您可以通过在 exec 调用中使用全局变量来做到这一点:
def my_exec(code):
exec('global i; i = %s' % code)
global i
return i
Run Code Online (Sandbox Code Playgroud)
这是滥用全局变量来跨越边界获取数据。
>>> my_exec('1 + 2')
3
Run Code Online (Sandbox Code Playgroud)
毋庸置疑,您永远不应该允许任何用户输入用于此功能的输入,因为它会带来极大的安全风险。
像这样的事情可以工作:
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
Run Code Online (Sandbox Code Playgroud)
这个想法是从内部函数中提取代码对象并基于它创建一个新函数。
当内部函数可以包含自由变量时,需要进行额外的工作。您还必须提取它们并传递给最后一个参数 ( closure) 中的函数构造函数。
| 归档时间: |
|
| 查看次数: |
18281 次 |
| 最近记录: |