2013-01-24 84 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中。 –

相關問題