如何在python中运行ipython脚本?

问题描述 投票:0回答:1

我想在python中运行ipython脚本,即:

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

那将打印

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

它存在吗?我搜索了文档,但似乎没有(很好)记录。

python ipython
1个回答
1
投票

简而言之,根据您想要做什么以及您希望包含多少IPython功能,您需要做更多。

您需要知道的第一件事是IPython将其代码分成块。每个块都有自己的结果。

如果您使用块,请使用此建议

如果你没有任何神奇的IPython为你提供并且不希望每个块给出任何结果,那么你可以尝试使用exec(compile(script, "exec"), {}, {})

如果你想要更多,你需要实际生成一个InteractiveShell实例,因为像%magic%%magic这样的功能将需要一个有效的InteractiveShell

在我的一个项目中,我有这个函数在InteractiveShell-instance中执行代码:https://github.com/Irrational-Encoding-Wizardry/yuuno/blob/master/yuuno_ipython/ipython/utils.py#L28

如果你想得到每个表达式的结果,

然后你应该使用ast-Module解析代码并添加代码以返回每个结果。您将在第34行以上链接的函数中看到这一点。以下是相关的,除了:

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)

而是为身体中的每个语句而不是最后一个语句执行此操作并将其替换为一些“printResult” - 转换将为您执行相同操作。

© www.soinside.com 2019 - 2024. All rights reserved.