您無法在常規控制檯中執行此操作。 iPython會保留一份源代碼的副本,以備日後再次查看,但標準Python控制檯不會。
只好從文件導入的功能,你也可以使用:
>>> import os.path
>>> import inspect
>>> print inspect.getsource(os.path.join)
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path
但是,僅僅是明確的,inspect.getsource()
將無法在交互式控制檯中輸入功能:
>>> def foo(): pass
...
>>> print inspect.getsource(foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 538, in findsource
raise IOError('could not get source code')
IOError: could not get source code
,因爲解釋器中沒有任何內容保留輸入(除了readline庫,可能會保存輸入歷史記錄,只是不能以inspect.getsource()
直接使用的格式)。
你正在做的這一切在一個控制檯,而不是在一個文件中的任何原因? –
不在控制檯中。在文件中,是的,但不是在控制檯中。 –
可能重複的[可以Python打印一個函數定義?](http://stackoverflow.com/questions/1562759/can-python-print-a-function-definition) –