• [记录]Python2.7使用argparse模块


    # -*- coding: utf8 -*-
    
    import argparse
    
    #ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
    #action:默认是store:保存值到参数名中;store_const:值存放在const中;store_true和store_false:值存为True或False;append:存为列表;append_const:存为列表,会根据const关键参数进行添加;count:统计参数出现的次数
    #nargs: 指定参数值得个数,值可以为整数N(N个),*(任意多个),+(一个或更多),值为?时,首先从命令行获得参数,若没有则从const获得,然后从default获得
    #const:保存一个常量
    #type:这个参数用来指定参数的类型
    #choices: 这个参数用来检查输入参数的范围
    #required: 当某个选项指定需要在命令中出现的时候用这个参数
    #help: 使用这个参数描述选项作用
    #dest: 这个参数相当于把位置或者选项关联到一个特定的名字
    #metavar: 这个参数用于help信息输出中
    
    parser = argparse.ArgumentParser(description="say something about this application !!")
    parser.add_argument("-a", "--age", type=str, dest='aaa', metavar=('123'), nargs="*", help="I can tell you how to set a name argument.")
    parser.add_argument("-b", "--bool", dest='bbb', help="I can tell you how to set a name argument.", action="store_true")
    parser.add_argument("-c", "--count", dest='ccc', help="this is an optional argument", type=int, choices=[0, 1, 2])
    parser.add_argument("-v", "--verbose", dest='ddd', action="count", default=0, help="increase output verbosity")
    result = parser.parse_args()
    answer = result.ccc**2
    
    if result.ddd >= 2:
        print "the square of {} equals {}".format(result.ccc, answer)
    elif result.ddd >= 1:
        print "{}^2 == {}".format(result.ccc, answer)
    else:
        print answer
    
    print result.aaa
    print result.bbb
    print result.ddd
    
    '''
    使用示例:
    #python args.py -b --count 2 -a 123 456 789 -vvvvv
    the square of 2 equals 4
    ['123', '456', '789']
    True
    5
    '''
    

      

  • 相关阅读:
    LeetCode 81 Search in Rotated Sorted Array II(循环有序数组中的查找问题)
    LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)
    LeetCode 79 Word Search(单词查找)
    LeetCode 78 Subsets (所有子集)
    LeetCode 77 Combinations(排列组合)
    LeetCode 50 Pow(x, n) (实现幂运算)
    LeetCode 49 Group Anagrams(字符串分组)
    LeetCode 48 Rotate Image(2D图像旋转问题)
    LeetCode 47 Permutations II(全排列)
    LeetCode 46 Permutations(全排列问题)
  • 原文地址:https://www.cnblogs.com/wsjhk/p/8435684.html
Copyright © 2020-2023  润新知