在interp中重新加载(更新)模块文件

2024-04-24 06:01:20 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个python脚本script.py,然后通过键入

import script

然后我通过键入以下内容来执行我的函数:

script.testFunction(testArgument)

到目前为止还不错,但是当我更改script.py时,如果我再次尝试导入,脚本不会更新。我必须从解释器中退出,重新启动解释器,然后导入新版本的脚本才能工作。

我该怎么做呢?


Tags: 函数pyimport版本脚本键入script解释器
3条回答

http://docs.python.org/library/functions.html#reload

reload(module)

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

您可以发出一个reload script,但这不会更新您现有的对象,也不会深入到其他模块中。

幸运的是,这是通过IPython解决的,这是一个更好的python shell,支持自动重新加载。

要在IPython中使用autoreloading,您必须首先键入import ipy_autoreload,或者将其永久放入~/.ipython/ipy_user_conf.py

然后运行:

%autoreload 1
%aimport script

%autoreload 1意味着加载了%aimport的每个模块都将在从提示符执行代码之前重新加载。但是,这不会更新任何现有对象。

请参阅http://ipython.org/ipython-doc/dev/config/extensions/autoreload.html以了解您可以做的更多有趣的事情。

另一个对我有很大帮助的解决方案是维护sys.modules键的副本,并在导入后弹出新模块以强制重新导入深层导入:

>>> oldmods = set(sys.modules.keys())
>>> import script
>>> # Do stuff
>>> for mod in set(sys.modules.keys()).difference(oldmods): sys.modules.pop(mod)
>>> import script

相关问题 更多 >