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

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

问题描述

是否可以编写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 <的高级python课程/a>建议将脚本放入与.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.

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

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