首页 > 解决方案 > 从 Python 脚本中启动 IPython 内核

问题描述

假设我有以下文件t.py

from IPython import get_ipython

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

如果我同时使用Pythonand运行它,会发生以下情况IPython

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

请注意,仅当使用 , 运行它时ipython,它get_ipython()才不是 None。

有没有办法从脚本中启动 IPython 内核,这样即使我将它作为 运行python t.pyget_ipython()也不会是 None?

标签: ipython

解决方案


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


推荐阅读