在IPython中自动加载模块

时间:2009-12-15 14:55:51

标签: python ipython

有没有办法让IPython自动重新加载所有更改的代码?在每个行在shell中执行之前,或者在特别请求它时失败。我正在使用IPython和SciPy进行大量的探索性编程,每当我更改它时,必须手动重新加载每个模块。

6 个答案:

答案 0 :(得分:207)

对于IPython版本3.1,4.x和5.x

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

默认情况下,您的模块将自动重新加载。这是doc:

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

答案 1 :(得分:81)

如上所述,您需要autoreload扩展名。如果您希望每次启动时都自动启动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

答案 2 :(得分:64)

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

...

有点难以弄清楚如何从尘土飞扬的错误报告中找到答案,但是:

它现在随附IPython!

import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help

...然后每次拨打your_mod.dwim()时,都会选择最新版本。

答案 3 :(得分:8)

如果你将ipython_config.py添加到〜/ .ipython / profile_default dir中,如下所示,那么自动重载功能将在ipython启动时加载(在2.0.0上测试):

print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"

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

答案 4 :(得分:2)

您可以使用:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod

答案 5 :(得分:1)

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

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