17.2. pydoc — 模块的线上帮助文档
目标: 从 Python 代码的模块和类中生成辅助文档。
pydoc
模块引入一个 Python 模块并在运行时通过其中的注释生成辅助文档。输出的内容包括含有任意注解的对象,类,类方法以及模块的函数。
以下为生成一份说明文档的例子
在命令行中运行 pydoc
命令,并将希望生成说明文档的模块名作为参数输入,随后控制台中就会展示出模块的说明文档(对于篇幅比较长的文档,如果显示终端配置了翻页选项,还可以进行翻页浏览)。例如,运行 pydoc atexit
,即可查看 atexit
模块的说明文档。
$ pydoc atexit
Help on built-in module atexit:
NAME
atexit - allow programmer to define multiple exit functions
to be executed upon normal program termination.
DESCRIPTION
Two public functions, register and unregister, are defined.
FUNCTIONS
register(...)
register(func, *args, **kwargs) -> func
Register a function to be executed upon normal program
termination
func - function to be called at exit
args - optional arguments to pass to func
kwargs - optional keyword arguments to pass to func
func is returned to facilitate usage as a decorator.
unregister(...)
unregister(func) -> None
Unregister an exit function which was previously
registered using
atexit.register
func - function to be unregistered
FILE
(built-in)
HTML 帮助文档
pydoc
可以生成一份 HTML 的输出,不论是写到本地目录的静态文件下还是开启一个 web 服务器在网上浏览,都是可以的。
$ pydoc -w atexit
这样做会在当前文件夹下生成 atexit.html
.
$ pydoc -p 5000
Server ready at http://localhost:5000/
Server commands: [b]rowser, [q]uit
server> q
Server stopped
这样做会启动一个 web 服务器监听 http://localhost:5000/
。服务器会在你浏览器中即时生成。b
命令会自动打开浏览器窗口,q
则会停止服务器。
交互式帮助
pydoc
还把 help()
函数放进了 __builtins__
,所以在 Python 解释器下我们可以用它得到相同的帮助信息。
$ python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>> help('atexit')
Help on module atexit:
NAME
atexit - allow programmer to define multiple exit functions
to be executed upon normal program termination.
...
参阅
- pydoc 标准库文档
inspect
--inspect
模块可以让一个对象以编程的方式检索文档字符串。
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。