Debugging 从Python模块运行代码,修改模块,然后在不退出interpeter的情况下再次运行

Debugging 从Python模块运行代码,修改模块,然后在不退出interpeter的情况下再次运行,debugging,testing,python,Debugging,Testing,Python,我希望能够打开一个pythonshell,执行模块中定义的一些代码,然后修改模块,然后在同一个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", "cre

我希望能够打开一个pythonshell,执行模块中定义的一些代码,然后修改模块,然后在同一个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 interpeter中的模块代码吗?

使用
imp.reload()


您总是可以编写一个模块来导入所有内容、定义虚拟变量等,然后每次重新打开解释器时,您只需从testsetup import*获取正确的上下文(或者执行
python-i test setup.py
而不只是
python
)。reload()也可在全局命名空间中使用,无需导入imp。
In [1]: import imp

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

Reload the module.  The module must have been successfully imported before.