【发布时间】:2016-01-29 07:09:24
【问题描述】:
我试试:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
返回 'TEST12344'[:2]
如何从函数中的exec返回值
【问题讨论】:
标签: python string python-2.7 exec
我试试:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
exec(s)
return s
print test("TEST12344","[:2]")
返回 'TEST12344'[:2]
如何从函数中的exec返回值
【问题讨论】:
标签: python string python-2.7 exec
exec() 不仅计算表达式,还执行代码。您必须在exec() 调用中保存参考。
def test(w, sli):
exec('s = "{}"{}'.format(w, sli))
return s
如果您只想计算表达式,请使用eval(),并保存对返回值的引用:
def test(w,sli):
s = "'{0}'{1}".format(w,sli)
s = eval(s)
return s
但是,我建议尽可能避免在任何实际代码中使用 exec() 和 eval()。如果您使用它,请确保您有充分的理由这样做。
【讨论】:
NameErrors
print 用作语句而不是函数可以看出,这里没有使用 Python 3。
考虑运行以下代码。
code = """
def func():
print("std out")
return "expr out"
func()
"""
如果您在 python 控制台上运行func(),输出将类似于:
>>> def func():
... print("std out")
... return "expr out"
...
>>> func()
std out
'expr out'
>>> exec(code)
std out
>>> print(exec(code))
std out
None
如你所见,返回值为 None。
>>> eval(code)
会产生错误。
import ast
import copy
def convertExpr2Expression(Expr):
Expr.lineno = 0
Expr.col_offset = 0
result = ast.Expression(Expr.value, lineno=0, col_offset = 0)
return result
def exec_with_return(code):
code_ast = ast.parse(code)
init_ast = copy.deepcopy(code_ast)
init_ast.body = code_ast.body[:-1]
last_ast = copy.deepcopy(code_ast)
last_ast.body = code_ast.body[-1:]
exec(compile(init_ast, "<ast>", "exec"), globals())
if type(last_ast.body[0]) == ast.Expr:
return eval(compile(convertExpr2Expression(last_ast.body[0]), "<ast>", "eval"),globals())
else:
exec(compile(last_ast, "<ast>", "exec"),globals())
exec_with_return(code)
【讨论】:
我在 2020 年在 Python 3.8 中的发现
在评估逻辑中:
a="1+99"
a=eval(a)
print(a) # output: 100
在执行逻辑中
exec ("a=33+110")
print(a) #output 143
【讨论】: