用于测试参数解析而不使用os.popen()污染docstring的shell脚本的Python doctest

hob*_*obs 8 python shell doctest argparse

有没有办法写一个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]
Run Code Online (Sandbox Code Playgroud)

不使用popen运行doctest.testmod()只会导致测试失败,因为脚本是在python shell而不是bash(或DOS)shell中运行的.

LLNL的高级python课程建议将脚本放在与.py模块分开的文件中.但是doctest字符串只测试模块,没有arg解析.我的os.popen()方法污染了Examples文档.有没有更好的办法?

dmi*_*nov 3

刚刚找到了一些看起来像您想要的答案的东西: shell-doctest

  • 看起来很可疑,仅限 Python 2。:-( (2认同)