在IPython中自动重新加载模块
有没有办法让IPython自动重新加载所有更改的代码? 在shell中执行每行之前,或者在特定请求时执行失败。 我正在使用IPython和SciPy进行大量的探索性编程,每当我改变它时,必须手动重新加载每个模块,这是相当痛苦的。
修订 – 请参阅下面的Andrew_1510的答案 ,因为IPython已经更新。
…
要弄清楚如何从一个满是灰尘的错误报告中find答案有点困难,但是:
它现在与IPython一起发货!
import ipy_autoreload %autoreload 2 %aimport your_mod # %autoreload? for help   …每当你打电话给your_mod.dwim() ,它都会select最新的版本。 
对于IPython版本3.1,4.x和5.x
  In [1]: %load_ext autoreload In [2]: %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时,你忘记了上面的所有 ipython ,试试: 
 import autoreload ?autoreload # Then you get all the above 
 如上所述,您需要自动重新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
如果将ipython_config.py添加到〜/ .ipython / profile_default目录下面,那么autoreloadfunction将在ipython启动时加载(在2.0.0版本上testing):
 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') 
您可以使用:
  import ipy_autoreload %autoreload 2 %aimport your_mod