如何检查打印的源代码
How to inspect source code of print
我可以使用 inspect.getsource(obj)
获取函数的源代码。
print(inspect.getsource(gcd))
打印gcd
函数的源代码。当我尝试以下操作时,它会抛出错误。
>>>print(inspect.getsource(print))
File "<stdin>", line 1
print(inspect.getsourcelines(print))
^
SyntaxError: invalid syntax
我能得到打印的源代码吗?;如果是如何?如果不是为什么?
回答添加比 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 and see how your built-in has been implemented. In my case, I almost always use CPython, so I'd start at the CPython directory.
因为我们知道我们正在寻找 builtin
模块,所以我们进入 /Python
目录并寻找看起来包含内置模块的东西。 bltinmodule.c
是一个安全的猜测。知道 print 必须被定义为可调用的函数,搜索 print(
然后我们跳到定义它的 builtin_print(Pyobject...。
2) 幸运地猜测内置函数名称约定并在代码库中搜索builtin_print
。
3) 使用在幕后发挥魔力的工具,例如 Puneeth Chaganti 的 Cinspect。
我可以使用 inspect.getsource(obj)
获取函数的源代码。
print(inspect.getsource(gcd))
打印gcd
函数的源代码。当我尝试以下操作时,它会抛出错误。
>>>print(inspect.getsource(print))
File "<stdin>", line 1
print(inspect.getsourcelines(print))
^
SyntaxError: invalid syntax
我能得到打印的源代码吗?;如果是如何?如果不是为什么?
回答添加比 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 and see how your built-in has been implemented. In my case, I almost always use CPython, so I'd start at the CPython directory.
因为我们知道我们正在寻找 builtin
模块,所以我们进入 /Python
目录并寻找看起来包含内置模块的东西。 bltinmodule.c
是一个安全的猜测。知道 print 必须被定义为可调用的函数,搜索 print(
然后我们跳到定义它的 builtin_print(Pyobject...。
2) 幸运地猜测内置函数名称约定并在代码库中搜索builtin_print
。
3) 使用在幕后发挥魔力的工具,例如 Puneeth Chaganti 的 Cinspect。