5

我希望能够打开 Python shell,执行模块中定义的一些代码,然后修改模块,然后在同一个 shell 中重新运行它而无需关闭/重新打开。

我尝试在修改脚本后重新导入函数/对象,但这不起作用:

Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from my_module import buggy_function, test_input
>>> buggy_function(test_input)
wrong_value  # Returns incorrect result

# Go to the editor, make some changes to the code and save them

# Thought reimporting might get the new version
>>> from my_module import buggy_function, test_input

>>> buggy_function(test_input)
wrong_value # Returns the same incorrect result

显然,重新导入并没有让我获得该功能的“新版本”。

在这种情况下,关闭解释器并重新打开它并不是什么大问题。但是,如果我正在测试的代码足够复杂,有时我必须做大量的导入对象和定义虚拟变量来创建一个可以充分测试代码的上下文。每次我进行更改时都必须这样做,这确实很烦人。

任何人都知道如何在 Python 解释器中“刷新”模块代码?

4

1 回答 1

8

使用imp.reload()

In [1]: import imp

In [2]: print imp.reload.__doc__
reload(module) -> module

Reload the module.  The module must have been successfully imported before.
于 2013-01-24T00:59:42.277 回答