I have code from this Question: Why is Python's eval() rejecting this multiline string, and how can I fix it?
def multiline_eval(expr, context={}):
"Evaluate several lines of input, returning the result of the last line"
tree = ast.parse(expr)
eval_exprs = []
exec_exprs = []
for module in tree.body:
if isinstance(module, ast.Expr):
eval_exprs.append(module.value)
else:
exec_exprs.append(module)
exec_expr = ast.Module(exec_exprs, type_ignores=[])
exec(compile(exec_expr, 'file', 'exec'), context)
results = []
for eval_expr in eval_exprs:
results.append(eval(compile(ast.Expression((eval_expr)), 'file', 'eval'), context))
return '\n'.join([str(r) for r in results])
When I use this code:
multiline_eval('''
print("Hello World1")
for a in range(5):
print(a)
print("Hello World2")
''')
The result is:
0
1
2
3
4
Hello World1
Hello World2
I am expecting this:
Hello World1
0
1
2
3
4
Hello World2
How can I change the code? I tried to change the code, but I was not successful.