python getopt的使用

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import getopt

def usage():
    print("usage");

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            #sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    print("ok verbose="+str(verbose)+",output="+output);

def test_getopt():
    args = '-a -b -cfoo -d bar a1 a2'.split()
    optlist, args = getopt.getopt(args, 'abc:d:')
    print optlist
    print args
    s = '--condition=foo --testing --output-file abc.def -x a1 a2'
    args = s.split()
    print args
    optlist, args = getopt.getopt(args, 'x', [ 'condition=', 'output-file=', 'testing'])
    print optlist
    print args


import argparse
def test_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)

# -v -o d:/test/out.txt -h
# -v -o d:/test/out.txt
if __name__ == "__main__":
    main()
    test_getopt();
    test_argparse();




你可能感兴趣的:(python)