简体   繁体   English

如何在python中运行ipython脚本?

[英]How to run ipython script in python?

I'd like to run ipython script in python, ie: 我想在python中运行ipython脚本,即:

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. 我搜索了该文档,但似乎没有(很好)记录该文档。

In short, depending on what you want to do and how much IPython features you want to include, you will need to do more. 简而言之,根据您要执行的操作以及要包含的IPython功能的数量,您将需要做更多的事情。

First thing you need to know is that IPython separates its code into blocks. 您需要知道的第一件事是IPython将其代码分成块。 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"), {}, {}) . 如果您没有IPython提供的任何功能,并且不想每个块给出任何结果,那么您可以尝试使用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 . 如果您还需要更多,则需要实际生成一个InteractiveShell实例,因为%magic%%magic类的功能需要一个有效的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 在我的一个项目中,我具有在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. 那么您应该使用ast -Module解析代码并添加代码以返回每个结果。 You will see this in the function linked above from line 34 onwards. 您将从上方的第34行起的链接中看到此功能。 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. 取而代之的是对正文中的每个语句(而不是最后一个语句)执行此操作,并用一些“ printResult”转换替换它,这将对您执行相同的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM