用于测试参数解析而不使用 os.popen() 污染文档字符串的 shell 脚本的 Python doctest [英] Python doctest for shell scripts that test argument parsing without polluting docstring with os.popen()

查看:28
本文介绍了用于测试参数解析而不使用 os.popen() 污染文档字符串的 shell 脚本的 Python doctest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法编写 python doctest 字符串来测试打算从命令行(终端)启动的脚本,该脚本不会使用 os.popen 调用污染文档示例?

Is there a way to write a python doctest string to test a script intended to be launched from the command line (terminal) that doesn't pollute the documentation examples with os.popen calls?

#!/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 中运行.

Running doctest.testmod() without using popen just causes a test failure because the script is run within a python shell instead of a bash (or DOS) shell.

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

The advanced python course at LLNL suggests putting scripts in files that are separate from .py modules. But then the doctest strings only test the module, without the arg parsing. And my os.popen() approach pollutes the Examples documentation. Is there a better way?

推荐答案

刚刚找到与您想要的答案相似的内容:shell-doctest.

Just found something looking like the answer you want: shell-doctest.

这篇关于用于测试参数解析而不使用 os.popen() 污染文档字符串的 shell 脚本的 Python doctest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆