从Python模块运行代码,修改模块,然后再次运行而不退出解释器

时间:2013-01-24 00:57:30

标签: debugging testing python

我希望能够打开一个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插件中“刷新”模块代码?

1 个答案:

答案 0 :(得分: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.