如何在脚本中使用 IPython 魔法来自动重新加载模块?

How to use IPython magic within a script to auto reload modules?

我正在尝试包含一些 IPython 内置魔术函数,以便在我 运行 脚本时自动重新加载模块。所以我试过这个:

if __IPYTHON__:
    %load_ext autoreload
    %autoreload 2

但是IPython returns:

%load_ext autoreload
^
SyntaxError: invalid syntax

知道如何解决这个问题吗?

感谢link胆子!!!在您的帮助下,我想出了以下解决方案:

from IPython import get_ipython
ipython = get_ipython()

if '__IPYTHON__' in globals():
    ipython.magic('load_ext autoreload')
    ipython.magic('autoreload 2')