2010-02-03 42 views
9

我正在Python交互式Shell(在Windows XP下的ActiveState ActivePython 2.6.4)中工作。我創建了一個我想要的功能。但是,我清除了屏幕,因此我無法返回查看功能定義。它也是一個多行功能,所以重新顯示行的向上箭頭的價值很小。反正有返回函數的實際代碼嗎?有「代碼」和「dir()顯示」func_code「屬性,但我不知道它們是否包含我需要的。在交互式shell中顯示函數定義

+1

我曾建議使用「幫助」功能,但後來意識到你想要的功能,而不僅僅是它的簽名的實際代碼。 – 2010-02-03 16:24:22

+0

我想獲得我在控制檯中編寫的所有代碼作爲文件,但至於收到的答案是不可能的...... sad – 2012-07-15 22:19:59

回答

8

不,__code__func_code是對編譯字節碼的引用 - 您可以反彙編它們(請參閱dis.dis),但不能回到Python源代碼。

唉,源代碼是簡單地走了,不隨地想起...:

>>> import inspect 
>>> def f(): 
... print 'ciao' 
... 
>>> inspect.getsource(f) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 694, in getsource 
    lines, lnum = getsourcelines(object) 
    File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 683, in getsourcelines 
    lines, lnum = findsource(object) 
    File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/inspect.py", line 531, in findsource 
    raise IOError('could not get source code') 
IOError: could not get source code 
>>> 

如果inspect不能得到它,這是一個漂亮的指示標誌。

如果你是使用GNU readline的平臺上(基本上,除了任何Windows)中,你可能會利用這一事實本身readline記得一些「歷史」,可以寫出來的文件... :

>>> readline.write_history_file('/tmp/hist.txt') 

然後閱讀該歷史文件 - 但是,我知道在Windows中無法做到這一點。

您可能希望使用一些具有更好內存功能的IDE,而不是「原始」命令解釋程序,尤其是在諸如Windows的平臺上。

+0

我同意IDE。但是shell看起來像一個DOS命令窗口,PHB並不問我在做什麼。 – 2010-02-03 16:11:06

+0

也許這是一個很好的功能請求空閒... – 2010-02-03 16:12:04

+0

ipython可能有助於豐富的IDE在DOS命令窗口,請參閱http://ipython.scipy.org/moin/ - 它是如此豐富,我失去了軌道現在大部分功能;-)。 – 2010-02-03 16:38:57

0

除非在activestate shell上有這樣做的方法,否則沒有辦法檢索您在shell中鍵入的確切代碼。至少在Linux上,使用由CPython提供的Python Shell,沒有特殊的方法來實現這一點。也許使用iPython。

func_code屬性是一個表示函數字節碼的對象,你可以從這個對象得到的唯一東西是字節碼本身,而不是「原始」代碼。

+0

在Linux上,'readline.write_history_file'會有所幫助 - 但不能在Windows上。 – 2010-02-03 16:07:45

1

不,不是真的。您可以將yourfunc.func_code.co_code(實際編譯的字節碼)寫入文件,然後嘗試使用decompyle或unpyc對它們進行反編譯,但兩個項目都很舊且無法維護,並且從不支持反編譯。

簡單地將函數寫入文件以開始使用它是非常容易的。

2

它已經很長時間了,但可能有人需要它。 getsource給出的源代碼:

>>> def sum(a, b, c): 
... # sum of three number 
... return a+b+c 
... 
>>> from dill.source import getsource 
>>> 
>>> getsource(sum) 
'def sum(a, b, c):\n # sum of three number\n return a+b+c\n' 

安裝dill運行pip install dill。要得到它的格式:

>>> fun = getsource(sum).replace("\t", " ").split("\n") 
>>> for line in fun: 
... print line 
... 
def sum(a, b, c): 
# sum of three number 
return a+b+c