有没有一种方法可以在Python解释器中查看函数、类或模块的源代码?(除了使用help查看文档和dir查看属性/方法)
如果你打算使用Python进行交互式操作,那么很难超越ipython。然后,您可以使用%psource
来打印任何已知函数的源代码。
In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"
输出结果甚至被着色了。您还可以直接使用%edit
在定义源文件上调用您的$EDITOR
。
In [3]: %edit ctypes.c_bool
import IPython; IPython.embed()
,这非常方便,在那个点设置断点并跳转到解释器中(我更喜欢 pdb)。不幸的是,这对于 Twisted 不相关。 - Skylar Saveland>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An IOError is
raised if the source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1