def SoS_exec(script, _dict=None, return_result=False):
'''Execute a statement.'''
if _dict is None:
_dict = env.sos_dict._dict
if not return_result:
exec(script, _dict)
return None
try:
stmts = list(ast.iter_child_nodes(ast.parse(script)))
if not stmts:
return
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"), _dict)
# then we eval the last one
res = eval(compile(ast.Expression(body=stmts[-1].value), filename="<ast>", mode="eval"), _dict)
else:
# otherwise we just execute the entire code
exec(script, _dict)
res = None
except SyntaxError as e:
raise SyntaxError(f"Invalid code {script}: {e}")
#if check_readonly:
# env.sos_dict.check_readonly_vars()
return res
#
# dynamic expression that cannot be resolved during parsing
# at prepare mode etc, and has to be resolved at run time.
#
评论列表
文章目录