[英]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
我可以獲取打印的源代碼嗎? 如果是,如何?,如果不,為什么?
回答以添加比Vault提供的欺騙目標更多的信息。
以下答案直接針對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.'
以及print
的type
:
>>> type(print)
<class 'builtin_function_or_method'>
更具體地說:
>>> print.__module__
'builtins'
不幸的是, getsource
不支持getsource
。
您可以選擇:
1)遍歷Python源代碼,並了解如何實現內置功能。 就我而言,我幾乎總是使用CPython,因此我將從CPython目錄開始。
既然我們知道我們正在尋找一個builtin
模塊,那么我們進入/Python
目錄,尋找看起來好像包含內置模塊的內容。 bltinmodule.c
是一個安全的猜測。 知道必須將print定義為可調用的函數,然后搜索print(
然后我們跳到buildin_print(Pyobject ...的定義位置)。
2)對內置函數名稱約定進行幸運的猜測,並在代碼存儲庫中搜索builtin_print
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.