从 Python 脚本中启动 IPython 内核

mar*_*lli 5 ipython

假设我有以下文件t.py

from IPython import get_ipython

if __name__ == '__main__':
    ip = get_ipython()
    if ip is not None:
        print('Found IPython')
Run Code Online (Sandbox Code Playgroud)

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

% python t.py
% ipython t.py 
Found IPython
Run Code Online (Sandbox Code Playgroud)

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

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

pai*_*aiv 4

IPython 启动新的交互式 shell,即您的代码将暂停,直到 IPython shell 终止。

您可以在单独的文件中放置启动器launcher.py

import IPython

if __name__ == '__main__':
    IPython.start_ipython(['t.py'])
Run Code Online (Sandbox Code Playgroud)
% python launcher.py
Found IPython
Run Code Online (Sandbox Code Playgroud)

有关嵌入 IPython 的其他选项,请参阅文档https://ipython.readthedocs.io/en/stable/interactive/reference.html#embedding-ipython