小编典典

在IPython中自动重新加载模块

python

有没有办法让IPython自动重新加载所有更改的代码?在外壳中执行每行之前,或者在明确要求时失败。我正在使用IPython和SciPy进行很多探索性编程,每当更改模块时都必须手动重新加载每个模块,这是很痛苦的。


阅读 156

收藏
2020-12-20

共1个答案

小编典典

对于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
2020-12-20