Python寫自動化之使用sphinx提取Python程式碼docstring
在使用Python時,一個特性是Python中的文件字串,文件字串又稱為DocStrings。使用文件字串可以為我們的模組、類、函式新增說明性文件,使程式更容易被看懂。這好像和其他語言中的註釋沒什麼區別,然而,Python中的文件字串特殊在於Python提供了相應的方法,可以將這些說明性的文件輸出。
假設有如下的函式:
defTest():''' | ##@function: test | ##@description:test | ##@return value:None | ##@logic:test | ##@warning:test '''我們使用 Test.__doc__ 就可以得到Test()函式的說明文件,並且,呼叫help函式,實際上得到的內容也是該函式的說明文件。也就是說,help(Test),實際上輸出的內容就是Test()函式的說明文件。import atf.plugin.DesktopCommonasDesktopCommonDesktopCommon.StopProcess("notepad")
Sphinx是一個第三方工具,可以提取Python程式碼中的說明文件,並生成html檔案。介紹一下如何用Sphinx生成Python程式碼的API文件。
首先需要安裝Sphinx,安裝的方法有多種,可以直接用easy_install 安裝,也可以用其他的方法安裝。安裝之後,需要在將python的scripts目錄新增到系統環境變數中,如 C:\\python27\\Scripts。
現在就可以生成Python檔案的文件了。
假設我們的程式碼檔案在D:\\test 目錄下面。
(1)在命令列視窗中進入D:\\test 目錄下,執行 sphinx-quickstart
之後sphinx會提示讓對專案進行一些設定,以生成專案的配置檔案,下面是一個推薦的配置:
>Root path for the documentation [.]:<ENTER>>Separate source and build directories (y/N)[n]: y >Name prefix for templates and static dir [_]:<ENTER執行完之後,會在當前目錄下生成source資料夾,並且source資料夾下會有conf.py 和 index.rst檔案>>Project name: an_example_pypi_project >Author name(s):AndrewCarter>Project version:0.0.1>Project release [0.0.1]:<ENTER>>Source file suffix [.rst]:<ENTER>>Name of your master document (without suffix)[index]:<ENTER>> autodoc: automatically insert docstrings from modules (y/N)[n]: y > doctest: automatically test code snippets in doctest blocks (y/N)[n]: n > intersphinx: link between Sphinx documentation of different projects (y/N)[n]: y > todo: write “todo” entries that can be shown or hidden on build (y/N)[n]: n > coverage: checks for documentation coverage (y/N)[n]: n > pngmath: include math, rendered as PNG images (y/N)[n]: n > jsmath: include math, rendered in the browser by JSMath(y/N)[n]: n > ifconfig: conditional inclusion of content based on config values (y/N)[n]: y >CreateMakefile?(Y/n)[y]: n >CreateWindows command file?(Y/n)[y]: n
(2)修改conf.py檔案。目的是確保python原始碼所在的包在系統路徑中可以找到。
將 sys.path.insert(0,os.path.abspath('.')) 改為 sys.path.insert(0,os.path.abspath('..')) ,並去掉註釋
(3)生成rst檔案
命令列下執行: sphinx-apidoc -o outputdir packagedir
其中:outputdir是source的目錄,packagedir是程式碼所在的目錄
(4)生成rst檔案後,就可以生成html檔案了。進入到source目錄下,執行:
sphinx-build -b html . ./output
會在source目錄下生成output資料夾,並且生成的html檔案都在output資料夾內。