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

use*_*260 8 python

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

Ben*_*ier 17

如果你打算以交互方式使用python,那么很难击败ipython.要打印任何已知功能的来源,您可以使用%psource.

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

输出甚至着色.您也可以直接$EDITOR使用定义源文件调用您的%edit.

In [3]: %edit ctypes.c_bool
Run Code Online (Sandbox Code Playgroud)


Dun*_*can 10

>>> 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
Run Code Online (Sandbox Code Playgroud)

  • 哇..太糟糕了,我们需要一个导入,一个打印,一个连接和一个索引,只是为了使它可读...仍然,谢谢*编辑*我读了这个后用检查模块玩了,看起来你可以使用"getsource"而不是"getsourcelines"并跳过索引,即print(''.join(inspect.getsource(obj))) (2认同)