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

Cla*_*ell 5 python testing debugging

我希望能够打开一个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
Run Code Online (Sandbox Code Playgroud)

显然重新导入并没有让我获得该功能的"新版本".

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

任何人都知道如何在Python interpeter中"刷新"模块代码?

Ash*_*ary 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.
Run Code Online (Sandbox Code Playgroud)