【问题标题】:Start IPython kernel from within Python script从 Python 脚本中启动 IPython 内核
【发布时间】:2021-06-21 18:22:08
【问题描述】:

假设我有以下文件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()吗?
  • 是的,得到了​​ ``` warn("The IPython.kernel package has been deprecated since IPython 4.0." NOTE: 当使用 ipython kernel 入口点时,Ctrl-C 将不起作用。退出,你必须明确退出这个进程,要么从客户端发送“退出”,要么在类 UNIX 环境中使用 Ctrl-\。要了解更多信息,请参阅 github.com/ipython/ipython/issues/2049 要将另一个客户端连接到此内核,使用:--existing kernel-15293.json ```

标签: ipython


【解决方案1】:

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 您可以捕获具有code 值的SystemExit 异常,然后捕获具有该值的sys.exit
  • 你的意思是把它放在launcher.py 中吗?我试过了,它不适合我
  • 是的,您可以捕获SystemExit 并在launcher.py 中返回其代码,但t.py 仍会打印堆栈跟踪。
猜你喜欢
  • 2015-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多