【发布时间】:2012-04-15 23:07:52
【问题描述】:
有没有办法编写 python doctest 字符串来测试旨在从命令行(终端)启动的脚本,该脚本不会使用 os.popen 调用污染文档示例?
#!/usr/bin/env python
# filename: add
"""
Example:
>>> import os
>>> os.popen('add -n 1 2').read().strip()
'3'
"""
if __name__ == '__main__':
from argparse import ArgumentParser
p = ArgumentParser(description=__doc__.strip())
p.add_argument('-n',type = int, nargs = 2, default = 0,help = 'Numbers to add.')
p.add_argument('--test',action = 'store_true',help = 'Test script.')
a = p.parse_args()
if a.test:
import doctest
doctest.testmod()
if a.n and len(a.n)==2:
print a.n[0]+a.n[1]
在不使用 popen 的情况下运行 doctest.testmod() 只会导致测试失败,因为脚本是在 python shell 而不是 bash(或 DOS)shell 中运行的。
LLNL 的高级 Python 课程建议将脚本放在与 .py 模块分开的文件中。但随后 doctest 字符串仅测试模块,没有 arg 解析。我的 os.popen() 方法污染了示例文档。有没有更好的办法?
【问题讨论】:
-
我是否遗漏了什么或者可以通过添加
main函数来解决这个问题?在if __main__块中进行参数解析,然后调用main(parsed_args) -
不幸的是,这不会改变任何事情。 main 函数并不特殊。将 if main 中的一些内容分解成一个单独的函数根本不会改变 doctest 的行为。您仍然不能像 shell 命令一样运行它,因为该脚本旨在被使用(并记录在案)。
标签: python shell argparse doctest