在 IPython 中自动重新加载模块 [英] Autoreload of modules in IPython
问题描述
有没有办法让 IPython 自动重新加载所有更改的代码?要么在 shell 中执行每一行之前,要么在特别请求时失败.我正在使用 IPython 和 SciPy 进行大量探索性编程,每次更改每个模块时都必须手动重新加载它,这非常痛苦.
Is there a way to have IPython automatically reload all changed code? Either before each line is executed in the shell or failing that when it is specifically requested to. I'm doing a lot of exploratory programming using IPython and SciPy and it's quite a pain to have to manually reload each module whenever I change it.
推荐答案
适用于 IPython 3.1、4.x 和 5.x 版
For IPython version 3.1, 4.x, and 5.x
%load_ext autoreload
%autoreload 2
然后您的模块将默认自动重新加载.这是文档:
Then your module will be auto-reloaded by default. This is the 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
时忘记所有上述内容,请尝试:
There is a trick: when you forget all of the above when using ipython
, just try:
import autoreload
?autoreload
# Then you get all the above
这篇关于在 IPython 中自动重新加载模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!