[英]Why can not we inspect the source code of the `__builtins__` module?
為什么我不能檢查__builtins__
模塊的源代碼?
>>> import inspect
>>> inspect.getsource(__builtins__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python2.7/inspect.py", line 526, in findsource
file = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 403, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module '__builtin__' (built-in)> is a built-in module
我經歷了這個談話,但沒有幫助。
如果我能很好地解釋這一點,那就不會發生:
>>> help(inspect.getsource)
Help on function getsource in module inspect:
getsource(object)
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
IOError is raised if the source code cannot be retrieved.
您只能以這種方式檢查Python源。 內置模塊和使用C API編寫的擴展模塊中沒有任何源,因此無法對其進行檢查。 (當編譯C代碼時,結果可能包含一些調試信息,包括用於構建它的文件的本地路徑名,但其中不包括實際的源文本。)
請注意,直接在文檔中鏈接的函數上方, getsourcefile
表示:
如果對象是內置模塊,類或函數,則將失敗並顯示
TypeError
。
而且,您可能會猜到(或可以通過查看docs鏈接的inspect.py
進行驗證), getsourcefile
在getsource
使用了getsourcefile
。
如果您是在計算機上本地構建Python,並在構建后將源代碼保留在那里,那么有一個項目可以找到用於構建每個模塊的C源代碼,但我找不到它(我認為它位於現在-長死不救的Berlios或Sourceforge),而且我認為它不會在2.4天后更新。
編寫您自己的模塊以在github存儲庫中查找源代碼可能並不難,或者更好的是,在您自己的github存儲庫本地副本中查找源代碼。 (這比依賴於本地構建的Python要好得多……)您甚至可以擴展它,以使用setuptools
信息來查找遵循某些常見模式的pip
安裝的擴展模塊的源。 但是據我所知,沒有人發布過這樣的模塊。
如果您想自己構建類似的東西,請參閱此概念的快速和骯臟的證明 。 盡管您可能想使用git
或Github API而不是抓取,並且希望能夠搜索本地存儲庫(如果找不到它,則可以克隆它)和/或在運行之間緩存內容,等等。 ,這既顯示了它的簡單性,又顯示了它需要多少特殊外殼。
因此,最好的選擇是克隆存儲庫並手動查找內容,或者直接在github上瀏覽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.