How to use getopt/OPTARG in Python? How to shift arguments if too many arguments (9) are given?

后端 未结 3 1064
猫巷女王i
猫巷女王i 2021-01-31 09:25

How to use getopt/optarg in Python?

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 10:11

    A google search would have helped. Have a look at the getopt and argparse modules in the standard library:

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print args.accumulate(args.integers)
    

    Then run it as expected:

    $ prog.py -h
    usage: prog.py [-h] [--sum] N [N ...]
    
    Process some integers.
    
    positional arguments:
     N           an integer for the accumulator
    
    optional arguments:
     -h, --help  show this help message and exit
     --sum       sum the integers (default: find the max)
    

    When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:

    $ prog.py 1 2 3 4
    4
    
    $ prog.py 1 2 3 4 --sum
    10
    

    This is straight from the standard library.

提交回复
热议问题