有没有一种方法可以编写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()方法会污染示例文档。有更好的方法吗?

最佳答案

刚找到一个你想要的答案:
shell-doctest

07-24 19:02
查看更多