pydoc
Ka-Ping Yee 曾創建了一個相當著名的模塊,名叫 pydoc (比較而言: pydoc 可以做到 perldoc 所能做的任何事,并且做得更好、更漂亮:-)。對于 Python 2.1 來說, pydoc (以及它支持的 inspect )是標準庫的一部分。而對于使用 Python 1.5.2、1.6 或者 2.0 版本的用戶來說,下載并安裝 pydoc 也很簡單 ― 請立即下載(請參閱 參考資料)。
作為提供給閱讀這篇 Python 文章的任何初學者的背景資料,Python 一直有些半正式的文檔標準。這些標準并沒有試圖過度地限制開發者,而是給開發者提供“一種明顯的寫文檔的方法。”幸運的是,通常情況下,Python 開發者所寫的文檔比使用其它語言的典型開發者所寫的要好得多。
Python 文檔之所以“優秀”的主要因素是使用所謂的“docstring”。雖然 docstring 實際上只是一個被稱為 _doc_ 的變量,但還是有一個普遍使用的創建它們的快捷方式:只要在模塊、函數 def 、類定義或方法 def 的頭部放入一個簡單的由(三重)引號括起來的字符串。此外,還有幾個接近標準的模塊級的“魔術”變量名被經常使用。盡管那些文檔規則不太正式,但幾乎所有第三方的模塊和標準模塊的文檔都使用相同的模式。讓我們來看一個使用大部分元素的簡化示例:
清單 1: 附帶典型文檔的模塊 mymod.py
#!/usr/bin/python"""Show off features of [pydoc] moduleThis is a silly module todemonstrate docstrings"""__author__ = 'David Mertz'__version__= '1.0'__nonsense__ = 'jabberwocky'class MyClass: """Demonstrate class docstrings""" def __init__ (self, spam=1, eggs=2): """Set default attribute values only Keyword arguments: spam ― a processed meat product eggs ― a fine breakfast for lumberjacks """ self.spam = spam self.eggs = eggs
pydoc 模塊利用了 Python 文檔的約定,又使用了一些有關 Python 導入、繼承和其它類似的實用知識。此外, pydoc 有絕對的天賦可以使自己在不同的操作模式下被使用(馬上就能看到更多有關這個論點的資料)。讓我們用一些時間,看看通過 OS 命令行調用的 manpage 風格的用法。
假設您已將上述模塊 mymod 安裝在您的系統上,但不知道它有什么用處(在示例中并不多)。您可以閱讀源代碼,不過更簡單的方法可能是:
清單 2:獲取‘manpage'風格的文檔
% pydoc.py mymodPython Library Documentation: module mymodNAME mymod - Show off features of [pydoc] moduleFILE /articles/scratch/cp18/mymod.pyDESCRIPTION This is a silly module to demonstrate docstringsCLASSES MyClass class MyClass | Demonstrate class docstrings | | __init__(self, spam=1, eggs=2) | Set default attribute values only | | Keyword arguments: | spam ― a processed meat product | eggs ― a fine breakfast for lumberjacksDATA __author__ = 'David Mertz' __file__ = './mymod.pyc' __name__ = 'mymod' __nonsense__ = 'jabberwocky' __version__ = '1.0'VERSION 1.0AUTHOR David Mertz
新聞熱點
疑難解答