Ven*_*esh 0 python inspect python-2.7
我可以使用inspect.getsource(obj).
print(inspect.getsource(gcd))
Run Code Online (Sandbox Code Playgroud)
它打印gcd函数的源代码。当我尝试以下操作时,它会引发错误。
>>>print(inspect.getsource(print))
File "<stdin>", line 1
print(inspect.getsourcelines(print))
^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)
我可以得到打印的源代码吗?如果是,如何?,如果否,为什么?
小智 5
回答添加比 vaultah 提供的欺骗目标更多的信息。
以下答案直接针对 3.x,我注意到您仍在使用 2.x。要对此进行良好的撰写,请查看此答案。
你实际上在这方面走在正确的道路上,但问题是这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.'
Run Code Online (Sandbox Code Playgroud)
哪里print是type:
>>> type(print)
<class 'builtin_function_or_method'>
Run Code Online (Sandbox Code Playgroud)
更具体地说:
>>> print.__module__
'builtins'
Run Code Online (Sandbox Code Playgroud)
多么不幸,它不受getsource.
您有以下选择:
1) 浏览Python 源代码,看看你的内置函数是如何实现的。就我而言,我几乎总是使用 CPython,所以我会从CPython 目录开始。
因为我们知道我们正在寻找一个builtin模块,所以我们进入/Python目录并寻找看起来像是包含内置模块的东西。 bltinmodule.c是一个安全的猜测。知道必须将 print 定义为可调用的函数,搜索print(并直接跳转到builtin_print(Pyobject...定义它的地方。
2) 对内置函数命名约定进行幸运猜测,并builtin_print在代码仓库中搜索。
3) 使用在幕后发挥作用的工具,例如 Puneeth Chaganti 的Cinspect。
| 归档时间: |
|
| 查看次数: |
2018 次 |
| 最近记录: |