簡體   English   中英

在交互式 shell 中顯示函數定義

[英]Display function definition in interactive shell

我在 Python 交互式 Shell(Windows XP 下的 ActiveState ActivePython 2.6.4)中工作。 我創建了一個可以滿足我需求的函數。 但是,我已經清除了屏幕,所以我無法返回查看函數定義。 它也是一個多行函數,因此重新顯示行的向上箭頭的值最小。 無論如何要返回函數的實際代碼嗎? dir() 顯示了“ code ”和“func_code”屬性,但我不知道它們是否包含我需要的內容。

不, __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 等平台上。

已經很長時間了,但可能有人需要它。 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

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

將您的函數簡單地寫入文件開始變得非常容易。

除非有辦法在 activestate shell 上執行此操作,否則無法檢索您在 shell 上鍵入的確切代碼。 至少在 Linux 上,使用 CPython 提供的 Python Shell 沒有特殊的方法可以實現這一點。 也許使用 iPython。

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

您可以嘗試按“ctrl+r”(即我在 bash 中反向搜索)然后輸入

def <name of your function> 

然后按 enter ,它可能會顯示函數定義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM