【问题标题】:How to inspect source code of print如何检查打印源代码
【发布时间】:2015-03-05 03:11:04
【问题描述】:

我可以使用inspect.getsource(obj)获取函数的源代码。

print(inspect.getsource(gcd))

它打印gcd 函数的源代码。当我尝试以下操作时,它会引发错误。

>>>print(inspect.getsource(print))

  File "<stdin>", line 1
     print(inspect.getsourcelines(print))
                                 ^
  SyntaxError: invalid syntax

我可以得到 print 的源代码吗?如果是,如何?如果不是,为什么?

【问题讨论】:

  • 不行,因为print是一个函数,用C写的。inspect只能获取Python函数的源码。
  • 您知道python是开源的,因此整个源代码都可以在线获得,对吧?您可以直接从存储库中获取它,而不是使用inspect(这会引发语法错误,因为print 是python 2 中的语言关键字,而不是python 3 中的函数)。
  • @Martin Pieters 这不是那个问题的重复。我无法获得打印的源代码。我只想看看 print 的实现,而不是所有的内置函数,我想知道这个错误的原因。怎么可能是那个问题的重复?
  • 我会问一个不同的问题:为什么?您想了解有关 print 的什么信息?顺便说一句,您可以使用from __future__ import print_function 在python 2 中使用打印功能,但它的行为与print 语句不同。

标签: python python-2.7 inspect


【解决方案1】:

回答添加比 vaultah 提供的欺骗目标更多的信息。

以下答案直接针对 3.x,我注意到您仍在使用 2.x。有关这方面的精彩文章,请查看answer

您实际上在这方面走在正确的道路上,但问题是print 是内置的,所以inspect.getsource 在这里对您没有多大用处。

也就是说:

>>> inspect.getsource.__doc__
'Return the text of the source code for an object.

The argument may be a module, class, method, function, traceback, frame,    
or code object.  The source code is returned as a single string.  An
OSError is raised if the source code cannot be retrieved.'

其中print 属于type

>>> type(print)
<class 'builtin_function_or_method'>

更具体地说:

>>> print.__module__
'builtins'

很遗憾,getsource 不支持。

你有选择:

1) 浏览Python source code,看看你的内置是如何实现的。就我而言,我几乎总是使用 CPython,所以我会从 CPython directory 开始。

因为我们知道我们正在寻找一个builtin 模块,所以我们进入/Python 目录并寻找看起来包含内置模块的东西。 bltinmodule.c 是一个安全的猜测。知道 print 必须被定义为可调用的函数,搜索 print( 并直接跳到定义它的 builtin_print(Pyobject...

2) 对内置函数命名约定进行幸运猜测,并在代码仓库中搜索builtin_print

3) 使用能够在幕后发挥作用的工具,例如 Puneeth Chaganti 的 Cinspect

【讨论】:

  • 您的答案对 Python 3.x 有效,但 OP 使用的是 Python 2.7,其中print 是一个语句。
  • @brunodesthuilliers 是的,我在发帖后注意到了这一点。我必须跑去处理一些重要的事情,稍后再编辑。
猜你喜欢
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多