这个问题在这里已经有答案了:

有没有办法让 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

其他提示

如上所述,您需要 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')

以及可选警告,以防您需要利用已编译的 Python 代码 .pyc 文件:

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

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

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

...

从满是灰尘的错误报告中找出如何到达那里有点困难,但是:

它现在随 IPython 一起提供!

import ipy_autoreload
%autoreload 2
%aimport your_mod

# %autoreload? for help

...然后每次你打电话 your_mod.dwim(), ,它将选择最新版本。

如果您使用如下行将 ipython_config.py 添加到 ~/.ipython/profile_default 目录中,则自动重新加载功能将在 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')

您可以使用:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top