在Python解释器中,有没有一种方法可以查看函数、类或模块的源代码?

8
有没有一种方法可以在Python解释器中查看函数、类或模块的源代码?(除了使用help查看文档和dir查看属性/方法)

你有源代码。是什么阻止了你查看源代码? - S.Lott
2
S. Lott:我想我正在寻找一些比弹出文件浏览器/终端,导航并打开另一个文本编辑器更方便的东西,特别是当我已经在使用某个模块时。 - user379260
@wkat12:你没有使用编辑器吗?显然,我完全不理解你的用例。请更新你的问题,提供关于你正在做什么以及为什么没有运行编辑器的额外信息。 - S.Lott
S.Lott:- 我使用 Aptana。但它打开的是我正在工作的文件目录,而不一定是我正在导入的文件目录。 - user379260
@wkat12:什么?你用的是没有Windows的系统吗?我真的无法理解你在做什么,为什么不能使用编辑器或打开多个窗口。请更新问题描述你正在做什么。 - S.Lott
2个回答

19

如果你打算使用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

不能把它作为正常答案接受,但是没错,IPython 很诱人。 - user379260
@gnibbler:我不知道,我认为它是附加在scipy/numpy模块上的,而且那些模块对我来说需要更长时间的理解,超出了我的准备范围,但现在看起来它是独立的。另外,如果你正在编写可以从终端运行的代码,你可能要注意任何不兼容性。不过我可能会再试一次 :) - user379260
有时候你必须使用控制台,而不能使用IPython ;) - Skylar Saveland
@SkylarSaveland:你的意思是你不是从命令行运行ipython吗? - Benjamin Bannier
@honk 是的,你可以在最新版本中 import IPython; IPython.embed(),这非常方便,在那个点设置断点并跳转到解释器中(我更喜欢 pdb)。不幸的是,这对于 Twisted 不相关。 - Skylar Saveland
显示剩余2条评论

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

2
哇...太糟糕了,我们需要一个导入(import)、一个打印(print)、一个连接(join)和一个索引(index),才能使它可读...不过还是谢谢。编辑 在阅读这篇文章后,我尝试使用inspect模块进行了一些实验,看起来你可以使用"getsource"代替"getsourcelines",并跳过索引操作,即print(''.join(inspect.getsource(obj)))。 - user379260
似乎对于内置类无法正常工作。 - ATL_DEV

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接