有没有办法让IPython自动重载所有更改的代码?要么在shell中执行每一行之前执行,要么在被特别要求执行时执行失败。我使用IPython和SciPy进行了大量探索性编程,每当我更改每个模块时,都必须手动重新加载它,这非常痛苦。


当前回答

对于IPython 3.1版,4。X和5.x

%load_ext autoreload
%autoreload 2

然后您的模块将在默认情况下自动重新加载。医生说:

File:       ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py

Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open foo.py in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.

这里有一个技巧:当你在使用ipython时忘记了以上所有内容时,请尝试:

import autoreload
?autoreload
# Then you get all the above

其他回答

有一个扩展,但我还没有使用经验:

http://ipython.scipy.org/ipython/ipython/attachment/ticket/154/ipy_autoreload.py

修订-请参阅下面Andrew_1510的答案,因为IPython已经更新。

...

从满是灰尘的bug报告中找到答案有点困难,但是:

它现在与IPython一起发布!

import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help

... 然后,每次调用your_mod.dwim()时,它都会获取最新版本。

对于IPython 3.1版,4。X和5.x

%load_ext autoreload
%autoreload 2

然后您的模块将在默认情况下自动重新加载。医生说:

File:       ...my/python/path/lib/python2.7/site-packages/IPython/extensions/autoreload.py

Docstring:
``autoreload`` is an IPython extension that reloads modules
automatically before executing the line of code typed.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open foo.py in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the
object imported with ``from foo import ...`` was also updated.

这里有一个技巧:当你在使用ipython时忘记了以上所有内容时,请尝试:

import autoreload
?autoreload
# Then you get all the above

如上所述,您需要自动重载扩展。如果你想让它在每次启动ipython时自动启动,你需要将它添加到ipython_config.py启动文件中:

可能需要先生成一个:

ipython profile create

然后在~/.ipython/profile_default/ipython_config.py中包含这些行:

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')

还有一个可选的警告,以防你需要利用.pyc文件中编译的Python代码:

c.InteractiveShellApp.exec_lines.append('print("Warning: disable autoreload in ipython_config.py to improve performance.")')

编辑:以上内容适用于0.12.1和0.13版本

你可以使用:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod