您不能在常规控制台中执行此操作。iPython 会保留一份源代码副本,以防您以后想再次查看它,但标准 Python 控制台不会。
如果您从文件中导入函数,您可以使用inspect.getsource()
:
>>> 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()
)。