有没有办法编写 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() 方法污染了示例文档。有没有更好的办法?