从Python脚本中启动IPython内核

5
假设我有以下文件 t.py:
from IPython import get_ipython

if __name__ == '__main__':
    ip = get_ipython()
    if ip is not None:
        print('Found IPython')

这是在PythonIPython 中运行该程序的结果:

% python t.py
% ipython t.py 
Found IPython

请注意,只有在使用 ipython 运行时,get_ipython() 才不是 None。
是否有一种方法可以在脚本内部启动 IPython 内核,以便即使我将其作为 python t.py 运行,那么 get_ipython() 也不会是 None?

你尝试过调用 IPython.start_kernel() 吗? - shx2
是的,并收到警告:“自IPython 4.0以来,IPython.kernel软件包已被弃用。”注意:当使用ipython kernel入口点时,Ctrl-C将不起作用。要退出,必须通过向客户端发送“quit”或在类UNIX环境中使用Ctrl-\ 显式退出此过程。要了解更多信息,请参见https://github.com/ipython/ipython/issues/2049 要连接另一个客户端到此内核,请使用: --existing kernel-15293.json - ignoring_gravity
1个回答

4

IPython 开启新的交互式 Shell,也就是说,当 IPython shell 未停止时,您的代码将被暂停。

您可以在一个单独的文件(launcher.py)中拥有一个启动器:

import IPython

if __name__ == '__main__':
    IPython.start_ipython(['t.py'])

% python launcher.py
Found IPython

如果想了解嵌入 IPython 的其他选项,请查看文档 https://ipython.readthedocs.io/en/stable/interactive/reference.html#embedding-ipython


谢谢!我有一个问题 - 假设t.pysys.exit(1)结束。然后,运行python t.py将不会出现异常,并且返回代码将为1,而python launcher.py将抛出SystemExit错误并显示回溯。launcher.py能否保留t.py的退出代码? - ignoring_gravity
@ignoring_gravity 你可以捕获 SystemExit 异常,该异常具有 code 值,然后使用该值 sys.exit - paiv
你的意思是把那个放在 launcher.py 文件里吗?我尝试了一下,但好像没成功。 - ignoring_gravity
是的,在 launcher.py 中你可以捕获 SystemExit 并返回它的代码,但是 t.py 仍将打印堆栈跟踪。 - paiv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接