假设我在字符串中有一些 python 代码
code = """
a = 42
a
"""
and I exec
那串代码:
result = exec(code)
Then result
一直会None
。有没有办法获得最后一个表达式的值?在这种情况下,那就是5
, since a
是最后一个表情。
编辑:这是我所询问的功能的另一个示例。假设我们有 python 代码(存储在变量中code
)
a = 100
sqrt(a)
那么我怎样才能以这样的方式执行代码来给出结果10
- 那是,sqrt(a)
?
编辑编辑:另一个例子:我希望的代码exec
is
function_a()
function_b()
function_c()
有什么方法可以定义某种magic_exec
函数使得
magic_exec(code)
将为我提供以下价值function_c()
?
这个请求当然是有效的,因为我在创建基于Python的环境期间也需要这样的功能。我通过以下利用Python ast机制的代码解决了这个问题:
def my_exec(script, globals=None, locals=None):
'''Execute a script and return the value of the last expression'''
stmts = list(ast.iter_child_nodes(ast.parse(script)))
if not stmts:
return None
if isinstance(stmts[-1], ast.Expr):
# the last one is an expression and we will try to return the results
# so we first execute the previous statements
if len(stmts) > 1:
exec(compile(ast.Module(body=stmts[:-1]), filename="<ast>", mode="exec"), globals, locals)
# then we eval the last one
return eval(compile(ast.Expression(body=stmts[-1].value), filename="<ast>", mode="eval"), globals, locals)
else:
# otherwise we just execute the entire code
return exec(script, globals, locals)
代码应该是非常不言自明的,基本上就是这样
- 将脚本分成多个语句
- 如果最后一个是表达式,则将第一部分作为语句执行,最后一部分作为表达式执行。
- 否则将整个脚本作为语句执行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)