IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

使用docopt轻松实现python命令行参数处理

笑遍世界 2016-03-01 23:46:29 累计浏览 1,295 次
本机暂存

   前面认识的一个python库 docopt,可以使用__doc__来实现命令行参数的处理,使用起来非常简单;我也刚好有在命令行添加或删除testsuite/testcase的需求,所以写了一个demo文件。
PS:我才发现docopt有2年没更新了,好吧,还是可以继续用它。
直接上我的demo程序:  https://github.com/smilejay/python/blob/master/py2016/try_docopt.py

#!/usr/bin/env python
"""Just try docopt lib for python

Usage:
  try_docopt.py (-h | --help)
  try_docopt.py [options]

Examples:
  try_docopt.py -s +ts5,-ts2 -c +tc5,-tc3

Options:
  -h, --help
  -s, --testsuite suites    #add/remove some testsuites
  -c, --testcase cases      #add/remove some testcases

"""

from docopt import docopt

testsuites = ['ts1', 'ts2', 'ts3', 'ts4']
testcases = ['tc1', 'tc2', 'tc3', 'tc4']


def add_remove(tlist, opt_list):
    '''
    add/remove item in tlist.
    opt_list is a list like ['+ts5', '-ts2'] or ['+tc5', '-tc3'].
    '''
    flag = 0
    for i in opt_list:
        i = i.strip()
        if i.startswith('+'):
            tlist.append(i[1:])
        elif i.startswith('-'):
            if i[1:] in tlist:
                tlist.remove(i[1:])
            else:
                print 'bad argument: %s is not in %s' % (i[1:], tlist)
                flag = 1
        else:
            print 'bad argument: %s' % i
            flag = 1
    if flag:
        return flag
    else:
        return tlist

if __name__ == '__main__':
    args = docopt(__doc__)
    ts_arg = args.get('--testsuite')
    tc_arg = args.get('--testcase')
    if ts_arg:
        ts_opt_list = ts_arg.strip().split(',')
        testsuites = add_remove(testsuites, ts_opt_list)
    if tc_arg:
        tc_opt_list = tc_arg.strip().split(',')
        testcases = add_remove(testcases, tc_opt_list)
    if testsuites != 1 and testcases != 1:
        print 'ts: %s' % testsuites
        print 'tc: %s' % testcases

   执行效果:

Jay-Ali:py2016 jay$ python try_docopt.py -s +ts5,+ts8,-ts1 --testcase -tc3,+tc6
ts: ['ts2', 'ts3', 'ts4', 'ts5', 'ts8']
tc: ['tc1', 'tc2', 'tc4', 'tc6']
Jay-Ali:py2016 jay$
Jay-Ali:py2016 jay$ python try_docopt.py -s +ts5,+ts8,-ts1 --testcase -tc3,+tc6,-tc7
bad argument: tc7 is not in ['tc1', 'tc2', 'tc4', 'tc6']

   docopt的github地址:https://github.com/docopt/docopt
更多的example:https://github.com/docopt/docopt/tree/master/examples

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. 用Hyer来进行网站的抓取 (累计阅读 158,252)
  2. SmartSprites - 命令行形式的CSS Sprites生成器 (累计阅读 123,895)
  3. 配置Nginx+uwsgi更方便地部署python应用 (累计阅读 107,167)
  4. 程序员技术练级攻略 (累计阅读 35,472)
  5. python实现自动登录discuz论坛 (累计阅读 32,834)
  6. python编程细节──遍历dict的两种方法比较 (累计阅读 20,371)
  7. 每个程序员都应该学习使用Python或Ruby (累计阅读 17,919)
  8. Chrome和goagent的配置方法,你懂的 (累计阅读 16,843)
  9. 30分钟3300%性能提升――python+memcached网页优化小记 (累计阅读 13,742)
  10. 使用python爬虫抓站的一些技巧总结:进阶篇 (累计阅读 13,302)