我经常在Python解释器中测试我的模块,当我看到错误时,我会快速更新.py文件。但是我如何让它反映在解释器上呢?所以,到目前为止,我一直在退出并重新进入解释器,因为重新导入文件再次不适合我。


当前回答

不确定这是否完成了所有预期的事情,但你可以这样做:

>>> del mymodule
>>> import mymodule

其他回答

上面所有关于reload()或imp.reload()的答案都已弃用。

Reload()不再是python 3中的内置函数,并且imp. Reload()被标记为已弃用(参见help(imp))。

最好使用importlib.reload()。

不确定这是否完成了所有预期的事情,但你可以这样做:

>>> del mymodule
>>> import mymodule

在Python 3中,行为会发生变化。

>>> import my_stuff

... 用my_stuff做一些事情,然后:

>>>> import imp
>>>> imp.reload(my_stuff)

你会得到一个全新的,重新加载的my_stuff。

简短的回答:

尝试使用reimport:一个完整的Python重载。

再答:

看起来这个问题是在reimport发布之前被问到/回答的,reimport自称是“Python的全功能重载”:

This module intends to be a full featured replacement for Python's reload function. It is targeted towards making a reload that works for Python plugins and extensions used by longer running applications. Reimport currently supports Python 2.4 through 2.6. By its very nature, this is not a completely solvable problem. The goal of this module is to make the most common sorts of updates work well. It also allows individual modules and package to assist in the process. A more detailed description of what happens is on the overview page.

注意:虽然重新导入显式地支持Python 2.4到2.6,但我一直在2.7上尝试它,它似乎工作得很好。

这里有一个很好的解释,说明你的依赖模块不会被重新加载,以及可能产生的影响:

http://pyunit.sourceforge.net/notes/reloading.html

pyunit解决这个问题的方法是通过覆盖__import__来跟踪依赖模块,然后从sys. exe中删除每个模块。模块并重新导入。不过他们可能只是装弹而已。