簡體   English   中英

如何檢查打印源代碼

[英]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.'

以及printtype

>>> 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

3)使用在幕后發揮作用的工具,例如Puneeth Chaganti的Cinspect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM