Python ast.Interactive() Examples

The following are 7 code examples of ast.Interactive(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse(self, code, file_name, interactive=False):
        self.lexer.input(code)
        tree = self.parser.parse(lexer = self.lexer, debug=False)
        if errors:
            first_error = None
            for line, msg in errors:
                if line == -1:
                    print('{}\t{}'.format(file_name, msg))
                else:
                    print('{}:{}\t{}'.format(file_name, line, msg))
            del errors[:]
            self.parser.restart()
            self.lexer = IndentLexer()
            raise SyntaxError
        if interactive:
            return ast.Interactive(tree)
        else:
            return ast.Module(tree) 
Example #2
Source File: execeval.py    From altair with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def eval_block(code, namespace=None, filename="<string>"):
    """
    Execute a multi-line block of code in the given namespace

    If the final statement in the code is an expression, return
    the result of the expression.
    """
    tree = ast.parse(code, filename="<ast>", mode="exec")
    if namespace is None:
        namespace = {}
    catch_display = _CatchDisplay()

    if isinstance(tree.body[-1], ast.Expr):
        to_exec, to_eval = tree.body[:-1], tree.body[-1:]
    else:
        to_exec, to_eval = tree.body, []

    for node in to_exec:
        compiled = compile(Module([node], []), filename=filename, mode="exec")
        exec(compiled, namespace)

    with catch_display:
        for node in to_eval:
            compiled = compile(
                ast.Interactive([node]), filename=filename, mode="single"
            )
            exec(compiled, namespace)

    return catch_display.output 
Example #3
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_module(self):
        m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
        self.mod(m, "must have Load context", "single")
        m = ast.Expression(ast.Name("x", ast.Store()))
        self.mod(m, "must have Load context", "eval") 
Example #4
Source File: test_ast.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_module(self):
        m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
        self.mod(m, "must have Load context", "single")
        m = ast.Expression(ast.Name("x", ast.Store()))
        self.mod(m, "must have Load context", "eval") 
Example #5
Source File: execute.py    From reactivepy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _run_ast_nodes(self, nodelist, name):
        output_name = None
        if not nodelist:
            return True, output_name

        if isinstance(nodelist[-1], _assign_nodes):
            asg = nodelist[-1]
            if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
                target = asg.targets[0]
            elif isinstance(asg, _single_targets_nodes):
                target = asg.target
            else:
                target = None
            if isinstance(target, ast.Name):
                output_name = target.id
                nnode = ast.Expr(ast.Name(target.id, ast.Load()))
                ast.fix_missing_locations(nnode)
                nodelist.append(nnode)

        if isinstance(nodelist[-1], ast.Expr):
            to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
        else:
            to_run_exec, to_run_interactive = nodelist, []

        try:
            mod = ast.Module(to_run_exec)
            code = compile(mod, name, 'exec')
            if self._run_code(code):
                return True, output_name

            for node in to_run_interactive:
                mod = ast.Interactive([node])
                code = compile(mod, name, 'single')
                if self._run_code(code):
                    return True, output_name
        except BaseException:
            return True, output_name

        return False, output_name 
Example #6
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_module(self):
        m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
        self.mod(m, "must have Load context", "single")
        m = ast.Expression(ast.Name("x", ast.Store()))
        self.mod(m, "must have Load context", "eval") 
Example #7
Source File: interpreter.py    From Pyonic-interpreter with GNU General Public License v3.0 4 votes vote down vote up
def interpret_code(code):

    # # Setting this var lets pip be used from a thread other than its original import
    # import threading
    # _log_state = threading.local()
    # if not hasattr(_log_state, 'indentation'):
    #     _log_state.indentation = 0

    try:
        sys.stdout.can_omit = True
        # The input is first parsed as ast, then if the last statement
        # is an Expr compiled partially in single mode. This means
        # that the last statement output is printed, as in the normal
        # Python interpreter

        components = ast.parse(code).body

        # print('components are', components)

        # exec all but the last ast component in exec mode
        if len(components) > 1:
            for component in components[:-1]:
                c = compile(ast.Module([component]), '<stdin>', mode='exec')
                exec(c, user_locals, user_globals)

        # if the last ast component is an Expr, compile in single mode to print it
        if isinstance(components[-1], ast.Expr):
            c = compile(ast.Interactive([components[-1]]), '<stdin>', mode='single')
        else:
            c = compile(ast.Module([components[-1]]), '<stdin>', mode='exec')
        exec(c, user_locals, user_globals)

    except KeyboardInterrupt as e:
        print('')
        traceback.print_exc()
        osc.sendMsg(b'/interpreter', [b'keyboard_interrupted'], port=send_port,
                    typehint='b')
    except Exception as e:
        traceback.print_exc()
    finally:
        sys.stdout.can_omit = False

    complete_execution()

    # instructions = ast.parse(code)
    # if isinstance(instructions.body[-1], ast.Expr):
    #     exec('print({})'.format(instructions.body[-1].value.id))