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

时间: 2024-07-30 12:24:49

Python写自动化之使用sphinx提取Python代码docstring的相关文章

Python写自动化之写一个Windows 服务

Python 写windows 服务,需要使用 pywin32包. 直接上代码: #encoding=utf8 ''' Created on 2014-7-1 @author: wangmengnan ''' import os import sys import win32serviceutil import win32service import win32event class PythonService(win32serviceutil.ServiceFramework): #服务名 _

Python写自动化之logging日志写入

日志写入是我们日常工作中常用到的功能,我们可以直接使用写文件的方式来以自己的方式写日志,另外,当我们在一个比较大的项目中,涉及到日志写入时,一般会使用logging模块来进行日志的写入,第一步,先写一个单例,创建一个logger对象: def _instance(): global logger if logger is None: logging.config.fileConfig(os.path.join(util.get_current(), "logger.conf")) lo

Python写自动化之图标锁定到任务栏或删除图标

这个功能在windows上测试安装卸载时,有时会用到,网上查到的两种语言的版本如下: C#版: Shell shell = new Shell(); Folder folder = shell.NameSpace(Path.GetDirectoryName(appPath)); FolderItem app = folder.ParseName(Path.GetFileName(appPath)); string sVerb = isLock ? "锁定到任务栏(&K)" :

Python写自动化之启动进程并获取进程输出

当我们需要执行外部命令或自己写一个自动化执行器时,需要使用到启动进程并获取输出的操作 首先,我们启动进程采用Python的subprocess模块,为了保证标准输出和标准错误输出能够正常运行,启动两个线程来检测输出结果部分 class Daemon(threading.Thread): def __init__(self, workDir, logFunction=None, *args): threading.Thread.__init__(self) self.process = None

Python写自动化之构造Multipartform-data发请求

在HTTP协议的规范中会将http请求分为三个部分:状态行,请求头,请求体.在发送HTTP请求时,需要在请求头中注明发送的方法,这些方法包括:OPTIONS.GET.HEAD.POST.PUT.DELETE.TRACE.CONNECT.其中GET和POST是最为普遍被使用的.有关POST和GET的区别,知识库中已经有同学进行了表述,这里主要介绍一下multipart/form-data请求具体是怎么一回事. 在普通的HTML Form Post请求中,它会在头信息里使用Content-Lengt

Python写自动化之ini文件的读写

在我们写一些测试工具时,经常会需要使用到配置文件,此时一般选用ini文件是比较合适的 标准并且可以通过参数命名知道参数的含义,那么使用Python如何进行ini文件的读写呢? 首先看下,读取ini文件,我们直接使用Python自带的模块ConfigParser来进行配置文件的读写 看下代码吧 def ReadConfig(configPath): configDict = {} cf = ConfigParser.ConfigParser() cf.read(configPath) sessio

Python写自动化之获取文件的MD5值

使用Python 获取文件的MD5 值是一件很简单的事情,Python 提供了md5 和 hashlib 两个模块,都可以获取到文件的md5值. 代码如下: #获取文件的MD5值,适用于小文件 def getFileMD5(self,filepath): if self.isFile(filepath): f = open(filepath,'rb') md5obj = hashlib.md5() md5obj.update(f.read()) hash = md5obj.hexdigest()

Python写自动化之注册表的读写操作

Windows上的自动化测试经常会接触到对于注册表的读写操作问题,比如,获取一个程序的安装目录,一般情况下,我们可以去注册表的App Paths下去查找,这时就涉及到了注册表的读取操作,我们使用Python的_winreg模块来实现,代码如下: def reg_query(path, key): try: path = path.replace("/", "\\") rootName = path[:path.find("\\")] subPat

Python写自动化之SVN更新

在远程机器上执行脚本时,为了能够保证脚本的实时性,我们一般会将脚本存放到SVN上,远程机器通过SVN的操作去更新脚本: SVN更新脚本只需要2步就可以实现了,这个地方使用到pysvn库,看下实现 # 初始化client self.client = pysvn.Client() self.client.set_default_username(self.username) self.client.set_default_password(util.decrypt_des(self.password