〇、python中对应的argc, argv
需要模块:sys
参数个数:len(sys.argv)
脚本名:    sys.argv[0]
参数1:     sys.argv[1]
参数2:     sys.argv[2]

 

一、getopt

opts,args = getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] ) ,第三个参数可省略
短选项名后的冒号(:)表示该选项必须有附加的参数。如果没有:,-abc等价于-a -b -c;如果a有:,-abc等价于-a bc。
长选项名后的等号(=)表示该选项必须有附加的参数。
返回opts和args。
opts是一个参数选项及其value的元组[('-o', 'value'),('--option',''),...],opts可有重复项
args是一个除去有用参数外其他的命令行输入 [ 'a1', 'a2',... ]

 1 import getopt, sys
 2 
 3 def main():
 4     try:
 5         opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
 6     except getopt.GetoptError as err:
 7         # print help information and exit:
 8         print str(err) # will print something like "option -a not recognized"
 9         usage()
10         sys.exit(2)
11     output = None
12     verbose = False
13     for o, a in opts:
14         if o == "-v":
15             verbose = True
16         elif o in ("-h", "--help"):
17             usage()
18             sys.exit()
19         elif o in ("-o", "--output"):
20             output = a
21         else:
22             assert False, "unhandled option"
23     # ...
24 
25 if __name__ == "__main__":
26     main()

 

二、argparse

 参数输入错误时,自动生成help。

 1 import argparse
 2 parser = argparse.ArgumentParser()
 3 parser.add_argument("square", type=int, help="display a square of a given number")
 4 # type=int,可省略,缺省str
 5 parser.add_argument("-v", "--verbosity", action="store_true",help="increase output verbosity")
 6 #action="store_true",不需要参数值
 7 #parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],help="increase output verbosity")
 8 #type,choice可省
 9 #parser.add_argument("-v", "--verbosity", action="count", default=0,help="increase output verbosity")
10 #不需要参数值,default可省
11 args = parser.parse_args()
12 answer = args.square**2
13 if args.verbosity == 2:
14     print "the square of {} equals {}".format(args.square, answer)
15 elif args.verbosity == 1:
16     print "{}^2 == {}".format(args.square, answer)
17 else:
18     print answer

互斥参数选项

 1 import argparse
 2 
 3 parser = argparse.ArgumentParser(description="calculate X to the power of Y")
 4 group = parser.add_mutually_exclusive_group()
 5 group.add_argument("-v", "--verbose", action="store_true")
 6 group.add_argument("-q", "--quiet", action="store_true")
 7 parser.add_argument("x", type=int, help="the base")
 8 parser.add_argument("y", type=int, help="the exponent")
 9 args = parser.parse_args()
10 answer = args.x**args.y
11 
12 if args.quiet:
13     print answer
14 elif args.verbose:
15     print "{} to the power {} equals {}".format(args.x, args.y, answer)
16 else:
17     print "{}^{} == {}".format(args.x, args.y, answer)

不定数量参数

 1 import argparse
 2 
 3 parser = argparse.ArgumentParser(description='Process some integers.')
 4 parser.add_argument('integers', metavar='N', type=int, nargs='+',
 5                    help='an integer for the accumulator')
 6 parser.add_argument('--sum', dest='accumulate', action='store_const',
 7                    const=sum, default=max,
 8                    help='sum the integers (default: find the max)')
 9 
10 args = parser.parse_args()
11 #calling parse_args() will return an object with two attributes, integers and 
12 #accumulate. The integers attribute will be a list of one or more ints, and the 
13 #accumulate attribute will be either the sum() function, if --sum was specified 
14 #at the command line, or the max() function if it was not.
15 
16 print args.accumulate(args.integers)

parser.parse_args(['--sum', '7', '-1', '42'])
也可直接加参数

三、optparse

2.7开始废弃

四、docopt

非标准库,根据文档生成

try.docopt.org

 1 """Naval Fate.
 2  
 3 Usage:
 4   
 5 naval_fate.py ship new <name>...
 6   
 7 naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
 8   
 9 naval_fate.py ship shoot <x> <y>
10   
11 naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
12   
13 naval_fate.py (-h | --help)
14   
15 naval_fate.py --version
16  
17 Options:
18   
19 -h --help     Show this screen.
20   
21 --version     Show version.
22   
23 --speed=<kn>  Speed in knots [default: 10].
24   
25 --moored      Moored (anchored) mine.
26   
27 --drifting    Drifting mine.
28  
29 """
30 from docopt import docopt
31 
32 if __name__ == '__main__':
33     arguments = docopt(__doc__, version='Naval Fate 2.0')
34     print(arguments)
35 
36 #返回
37 {'--drifting': False,    'mine': False,
38  '--help': False,        'move': True,
39  '--moored': False,      'new': False,
40  '--speed': '15',        'remove': False,
41  '--version': False,     'set': False,
42  '<name>': ['Guardian'], 'ship': True,
43  '<x>': '100',           'shoot': False,
44  '<y>': '150'}

 

posted on 2015-08-07 11:07  perel  阅读(2203)  评论(0编辑  收藏  举报