0

I'd like to run ipython script in python, ie:

code='''a=1
b=a+1
b
c'''
from Ipython import executor
for l in code.split("\n"):
   print(executor(l))

that whould print

None
None
2
NameError: name 'c' is not defined

does it exists ? I searched the doc, but it does not seems to be (well) documented.

2

1 Answer 1

1

In short, depending on what you want to do and how much IPython features you want to include, you will need to do more.

First thing you need to know is that IPython separates its code into blocks. Each block has its own result.

If you use blocks use this advice

If you don't any magic IPython provides you with and don't want any results given by each block, then you could just try to use exec(compile(script, "exec"), {}, {}).

If you want more than that, you will need to actually spawn an InteractiveShell-instance as features like %magic and %%magic will need a working InteractiveShell.

In one of my projects I have this function to execute code in an InteractiveShell-instance: https://github.com/Irrational-Encoding-Wizardry/yuuno/blob/master/yuuno_ipython/ipython/utils.py#L28

If you want to just get the result of each expression,

then you should parse the code using the ast-Module and add code to return each result. You will see this in the function linked above from line 34 onwards. Here is the relevant except:

if isinstance(expr_ast.body[-1], ast.Expr):
    last_expr = expr_ast.body[-1]
    assign = ast.Assign(    # _yuuno_exec_last_ = <LAST_EXPR>
        targets=[ast.Name(
            id=RESULT_VAR,
            ctx=ast.Store()
        )],
        value=last_expr.value
    )
    expr_ast.body[-1] = assign
else:
    assign = ast.Assign(     # _yuuno_exec_last_ = None
        targets=[ast.Name(
            id=RESULT_VAR,
            ctx=ast.Store(),
        )],
        value=ast.NameConstant(
            value=None
        )
    )
    expr_ast.body.append(assign)
ast.fix_missing_locations(expr_ast)

Instead doing this for every statement in the body instead of the last one and replacing it with some "printResult"-transformation will do the same for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, exactly what i'm looking for. Do you replace ast.Expr by ast.Assign because you can't eval them ? I've got no luck with eval(compile(l,"<string>","eval") when l is an ast.Expr .
Exactly, it replaces the last statement of the block to an assignment in case it is an expression. I can then get its result. You have to do it to each statement.
I manage to eval Epr instead, see stackoverflow.com/questions/52819981/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.