2013-01-24 43 views
6

我希望能够打开Python shell,执行模块中定义的某些代码,然后修改模块,然后重新运行它在没有关闭/重新打开的同一个shell中。从Python模块运行代码,修改模块,然后再次运行而不退出中间件

我已经试过修改脚本后重新导入功能/对象,并且不工作:

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

你总是可以编写一个导入所有的模块,定义了虚拟变量,等等,然后每次重新解释,你只是从'进口testsetup *'得到(或者'python -i测试setup.py'而不是'python')。 – abarnert

回答

9

使用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. 
+0

reload()也可以在全局命名空间中使用,而不需要导入imp。 –

+0

@LieRyan只在py2x中。 –

相关问题