加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 23:00:05 所属栏目:安全 来源:网络整理
导读:有没有办法写一个 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
有没有办法写一个 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()方法污染了Examples文档.有没有更好的办法?

解决方法

刚发现一些看起来像你想要的答案:
shell-doctest.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读