• python 命令行參数解析


    本文是从我还有一个博客转载过来的,欢迎大家点击进去看一下,帮我添加点人气^_^


    选择模块

    依据python參考手冊的提示,optparse 已经废弃,应使用 argparse

    教程

    概念

    argparse 模块使用 add_argument 来加入可选的命令行參数,原型例如以下:

    ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) 
    Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
    
        name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. 
        action - The basic type of action to be taken when this argument is encountered at the command line. 
        nargs - The number of command-line arguments that should be consumed. 
        const - A constant value required by some action and nargs selections. 
        default - The value produced if the argument is absent from the command line. 
        type - The type to which the command-line argument should be converted. 
        choices - A container of the allowable values for the argument. 
        required - Whether or not the command-line option may be omitted (optionals only). 
        help - A brief description of what the argument does. 
        metavar - A name for the argument in usage messages. 
        dest - The name of the attribute to be added to the object returned by parse_args(). 
    
    

    上面的说明事实上不用看,直接看演示样例好了:

    只想展示一些信息

    # -*- coding: utf-8 -*-
    """
    argparse tester
    """
    import argparse
    
    parser = argparse.ArgumentParser(description='argparse tester')
    
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")
    
    args = parser.parse_args()
    
    if args.verbose:
        print "hello world"
    
    


    它会输出例如以下:

    $ python t.py
    $ python t.py -v
    hello world
    $ python t.py -h
    usage: t.py [-h] [-v]
    
    argparse tester
    
    optional arguments:
      -h, --help     show this help message and exit
      -v, --verbose  increase output verbosity
    

    这里 -v 是这个选项的简写。--verbose 是完整拼法,都是能够的

    help 是帮助信息。不解释了

    args = parse_args() 会返回一个命名空间,仅仅要你加入了一个可选项,比方 verbose。它就会把 verbose 加到 args 里去,就能够直接通过 args.verbose 訪问。

    假设你想给它起个别名,就须要在 add_argument 里加多一个參数 dest='vb'

    这样你就能够通过 args.vb 来訪问它了。

    action="store_true" 表示该选项不须要接收參数,直接设定 args.verbose = True,

    当然假设你不指定 -v。那么 args.verbose 就是 False

    但假设你把 action="store_true" 去掉,你就必须给 -v 指定一个值。比方 -v 1

    做个求和程序

    # -*- coding: utf-8 -*-
    """
    argparse tester
    """
    
    import argparse
    
    parser = argparse.ArgumentParser(description='argparse tester')
    
    parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
    parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
    parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True)
    
    
    args = parser.parse_args()
    
    print "Input:", args.numbers
    print "Result:"
    results = args.numbers
    
    if args.verbose:
        print "hello world"
    
    if args.sum:
        results = sum(args.numbers)
        print "tSum:tt%s" % results

    输出例如以下:

    [pan@pan-pc test]$ python t2.py -h
    usage: t2.py [-h] [-v] [-s] numbers [numbers ...]
    
    argparse tester
    
    positional arguments:
      numbers        numbers to calculate
    
    optional arguments:
      -h, --help     show this help message and exit
      -v, --verbose  increase output verbosity
      -s, --sum      sum all numbers
    [pan@pan-pc test]$ python t2.py 1 2 3 -s
    Input: [1, 2, 3]
    Result:
        Sum:        6
    

    注意到这此可选项 numbers 不再加上 “-” 前缀了。由于这个是位置选项

    假设把 nargs="+" 去掉,则仅仅能输入一个数字。由于它指定了number 选项的值个数

    假设把 type=int 去掉。则 args.numbers 就是一个字符串。而不会自己主动转换为整数

    注意到 --sum 选项的最后还加上了 default=True。意思是即使你不在命令行中指定 -s,它也会默认被设置为 True

    仅仅能2选1的可选项

    # -*- coding: utf-8 -*-
    """
    argparse tester
    """
    
    import argparse
    
    parser = argparse.ArgumentParser(description='argparse tester')
    #group = parser.add_mutually_exclusive_group()
    
    
    parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
    parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
    parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True)
    
    parser.add_argument('-f', '--format', choices=['int', 'float'], help='choose result format', default='int')
    
    args = parser.parse_args()
    
    print "Input:", args.numbers
    print "Result:"
    results = args.numbers
    
    if args.verbose:
        print "hello world"
    
    if args.format == 'int':
        format = '%d'
    else:
        format = '%f'
    
    if args.sum:
        results = sum(args.numbers)
        print 'tsum:tt%s' % (format % results)
    

    输出例如以下:

    [pan@pan-pc test]$ python t2.py 1 2 3 -f float
    Input: [1, 2, 3]
    Result:
        sum:        6.000000
    [pan@pan-pc test]$ python t2.py 1 2 3 -f double
    usage: t2.py [-h] [-v] [-s] [-f {int,float}] numbers [numbers ...]
    t2.py: error: argument -f/--format: invalid choice: 'double' (choose from 'int', 'float')
    

    在加入选项 -f 时,传入了 choices=['int', 'float'] 參数。表示该选项仅仅能从 int 或 float 中2选1

  • 相关阅读:
    leetcode 673. 最长递增子序列的个数 java
    leetcode 148. 排序链表 java
    leetcode 98. 验证二叉搜索树 java
    leetcode 29. 两数相除 java
    leetcode 234. 回文链表 java
    Valid Palindrome LeetCode Java
    Single Number II LeetCode Java
    Single Number LeetCode java
    Search in Rotated Sorted Array II LeetCode Java
    Search in Rotated Sorted Array leetcode java
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6999151.html
Copyright © 2020-2023  润新知