有没有办法从python解释器查看函数,类或模块的源代码?

时间:2010-06-29 19:05:41

标签: python

有没有办法从python解释器查看函数,类或模块的源代码? (除了使用帮助查看文档和目录以查看属性/方法)

2 个答案:

答案 0 :(得分:17)

如果您计划以交互方式使用python,那么很难超越ipython。要打印任何已知功能的来源,您可以使用%psource

In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"

输出颜色均匀。您还可以使用$EDITOR直接在定义的源文件上调用%edit

In [3]: %edit ctypes.c_bool

答案 1 :(得分:9)

>>> 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