Exemplo n.º 1
0
def test_code_runner():
    runner = CodeRunner()
    assert should_quiet("1+1;")
    assert not should_quiet("1+1#;")
    assert not should_quiet("5-2  # comment with trailing semicolon ;")
    assert runner.run("4//2\n") == 2
    assert runner.run("4//2;") is None
    assert runner.run("x = 2\nx") == 2
    assert runner.run(
        "def f(x):\n    return x*x+1\n[f(x) for x in range(6)]") == [
            1,
            2,
            5,
            10,
            17,
            26,
        ]

    # with 'quiet_trailing_semicolon' set to False
    runner = CodeRunner(quiet_trailing_semicolon=False)
    assert runner.run("4//2\n") == 2
    assert runner.run("4//2;") == 2
Exemplo n.º 2
0
def test_code_runner():
    assert should_quiet("1+1;")
    assert not should_quiet("1+1#;")
    assert not should_quiet("5-2  # comment with trailing semicolon ;")

    # Normal usage
    assert CodeRunner("1+1").compile().run() == 2
    assert CodeRunner("x + 7").compile().run({"x": 3}) == 10
    cr = CodeRunner("x + 7")

    # Ast transform
    import ast

    l = cr.ast.body[0].value.left
    cr.ast.body[0].value.left = ast.BinOp(left=l,
                                          op=ast.Mult(),
                                          right=ast.Constant(value=2))
    assert cr.compile().run({"x": 3}) == 13

    # Code transform
    cr.code = cr.code.replace(co_consts=(0, 3, 5, None))
    assert cr.run({"x": 4}) == 17
Exemplo n.º 3
0
match_nonwhite_space = re.compile("[^\\w\\d\\s.(]")
completer = rlcompleter.Completer(__main__.__dict__)


def pycomplete(source):
    revsource = source[::-1]
    match = match_nonwhite_space.search(revsource)
    if match:
        source = source[: -match.end()]
    completer.matches = []
    completer.complete(source, 0)
    return completer.matches


code_runner = CodeRunner(globals=__main__.__dict__, filename="<console>")


async def exec_code(
    code, syntax_check_passed, stdin_callback, stdout_callback, stderr_callback
):
    mod, last_expr = code_runner._split_and_compile(
        code, flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT  # type: ignore
    )
    syntax_check_passed()
    await sleep(0)
    with redirect_stdout(WriteStream(stdout_callback)), redirect_stderr(
        WriteStream(stderr_callback)
    ), redirect_stdin(ReadStream(stdin_callback)):
        # run first part
        if mod is not None: