I have code from this Question: Why is Python’s eval() rejecting this multiline string, and how can I fix it?
JavaScript
x
17
17
1
def multiline_eval(expr, context={}):
2
"Evaluate several lines of input, returning the result of the last line"
3
tree = ast.parse(expr)
4
eval_exprs = []
5
exec_exprs = []
6
for module in tree.body:
7
if isinstance(module, ast.Expr):
8
eval_exprs.append(module.value)
9
else:
10
exec_exprs.append(module)
11
exec_expr = ast.Module(exec_exprs, type_ignores=[])
12
exec(compile(exec_expr, 'file', 'exec'), context)
13
results = []
14
for eval_expr in eval_exprs:
15
results.append(eval(compile(ast.Expression((eval_expr)), 'file', 'eval'), context))
16
return 'n'.join([str(r) for r in results])
17
When I use this code:
JavaScript
1
8
1
multiline_eval('''
2
print("Hello World1")
3
4
for a in range(5):
5
print(a)
6
print("Hello World2")
7
''')
8
The result is:
JavaScript
1
9
1
0
2
1
3
2
4
3
5
4
6
Hello World1
7
Hello World2
8
9
I am expecting this:
JavaScript
1
8
1
Hello World1
2
0
3
1
4
2
5
3
6
4
7
Hello World2
8
How can I change the code? I tried to change the code, but I was not successful.
Advertisement
Answer
The code you’ve posted sorts the ast tree body in 2 buckets, the ast.Expr
s and the rest, and then processes them bucket-wise. So, you have to remove the “bucketing”. You could try something like the following:
JavaScript
1
13
13
1
import ast
2
3
def multiline_eval(expr, ctx={}):
4
results = []
5
for node in ast.parse(expr).body:
6
if isinstance(node, ast.Expr):
7
result = eval(compile(ast.Expression(node.value), '<string>', 'eval'), ctx)
8
results.append(result)
9
else:
10
module = ast.Module([node], type_ignores=[])
11
results.append(exec(compile(module, '<string>', 'exec'), ctx))
12
return 'n'.join(map(str, results))
13