如何获取python打印功能的源代码?

the*_*der 0 python

我正在尝试使用inspect获取python打印的源代码,但它抛出错误。有人可以告诉我如何获取python2.7打印语句的源代码。

inspect.getsourcefile(print)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-85-6158f5314751> in <module>()
----> 1 inspect.getsourcefile(print)

/usr/lib/python3.4/inspect.py in getsourcefile(object)
    569     Return None if no way can be identified to get the source.
    570     """
--> 571     filename = getfile(object)
    572     all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
    573     all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]

/usr/lib/python3.4/inspect.py in getfile(object)
    534         return object.co_filename
    535     raise TypeError('{!r} is not a module, class, method, '
--> 536                     'function, traceback, frame, or code object'.format(object))
    537 
    538 ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')

TypeError: <built-in function print> is not a module, class, method, function, traceback, frame, or code object

In [86]: inspect.getsourcefile(builtin.print)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-86-2d1fb60aac58> in <module>()
----> 1 inspect.getsourcefile(builtin.print)

NameError: name 'builtin' is not defined
Run Code Online (Sandbox Code Playgroud)

Ant*_*ine 7

print功能以C语言实现。这就是为什么您无法使用该inspect模块获取其源代码的原因。代码在这里:https : //github.com/python/cpython/blob/2.7/Python/bltinmodule.c#L1580

  • 如果有人想知道,这里是当前源代码的链接:https://github.com/python/cpython/blob/3.8/Python/bltinmodule.c#L1821 (2认同)