eval.py 文件源码

python
阅读 25 收藏 0 点赞 0 评论 0

项目:SoS 作者: vatlab 项目源码 文件源码
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.
#
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号