Python写自动化之使用sphinx提取Python代码docstring

在使用Python时,一个特性是Python中的文档字符串,文档字符串又称为DocStrings。使用文档字符串可以为我们的模块、类、函数添加说明性文档,使程序更容易被看懂。这好像和其他语言中的注释没什么区别,然而,Python中的文档字符串特殊在于Python提供了相应的方法,可以将这些说明性的文档输出。

假设有如下的函数:

def Test():
    '''
    | ##@function: test
    | ##@description:test
    | ##@return value:None
    | ##@logic:test
    | ##@warning:test
    '''
    import atf.plugin.DesktopCommon as DesktopCommon
    DesktopCommon.StopProcess("notepad")
我们使用 Test.__doc__ 就可以得到Test()函数的说明文档,并且,调用help函数,实际上得到的内容也是该函数的说明文档。也就是说,help(Test),实际上输出的内容就是Test()函数的说明文档。

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>
> Project name:
an_example_pypi_project
> Author name(s):
Andrew Carter
> 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
> Create Makefile? (Y/n) [y]:
n
> Create Windows command file? (Y/n) [y]:
n
运行完之后,会在当前目录下生成source文件夹,并且source文件夹下会有conf.py 和 index.rst文件

(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文件夹内。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sogouauto/article/details/44776715
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值