缘由:
因为在Python2.7之后Python不再对optparse模块进行扩展,并推荐使用argparse模块替代optparse模块对命令行进行解析。
The argparse module was added to Python 2.7 as a replacement for optparse. The implementation of argparse supports features that would not have been easy to add to optparse, and that would have required backwards-incompatible API changes, so a new module was brought into the library instead. optparse is still supported, but is not likely to receive new features.
搜索关键字:
python argparse
参考链接:
- https://docs.python.org/2/library/argparse.html
- https://docs.python.org/2/howto/argparse.html
- http://pymotw.com/2/argparse/
- https://mkaz.com/2014/07/26/python-argparse-cookbook/ #样例充足
- http://www.cnblogs.com/jianboqi/archive/2013/01/10/2854726.html #简单易懂
- http://www.cnblogs.com/linxiyue/p/3908623.html #全面的中文说明
- http://stackoverflow.com/questions/tagged/argparse
- =
- https://docs.python.org/2/library/argparse.html#action
- https://docs.python.org/2/library/functions.html#vars
学习/使用样例:
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse #1.创建解析器 parser = argparse.ArgumentParser() parser = argparse.ArgumentParser(prog='PROG') #默认为sys.argv[0],用来在help信息中描述程序的名称 parser = argparse.ArgumentParser(prog='PROG', description='Demo') parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve') #2.添加参数选项 #可选参数 #required:是否必选 parser.add_argument('--limit', required=True, type=int) #default:默认值 parser.add_argument('--limit', default=5, type=int) #位置参数(parse_args()运行时,会用'-'来认证可选参数,剩下的即为位置参数) parser.add_argument('filename') #nargs:参数的数量{整数N(N个),*(任意多个),+(一个或更多)} parser.add_argument('nums', nargs=2) parser.add_argument('nums', nargs='*') parser.add_argument('nums', nargs='?') parser.add_argument('nums', nargs=2, type=int) #type:参数类型 parser.add_argument('f', type=argparse.FileType('r')) args = parser.parse_args() for line in args.f: print( line.strip() ) # action={ store_true/store_false/count/append } 默认为store parser.add_argument('--verbose', '-v', action='count') parser.add_argument('-v', '--verbose', action='store_true', help='verbose flag' ) #choices:可供选择的值 parser.add_argument('throw', choices=['rock', 'paper', 'scissors']) #3.解析参数(有几种写法) ''' 最常见的空格分开: >>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-x') >>> parser.add_argument('--foo') >>> parser.parse_args('-x X'.split()) Namespace(foo=None, x='X') >>> parser.parse_args('--foo FOO'.split()) Namespace(foo='FOO', x=None) 长选项用=分开: >>> parser.parse_args('--foo=FOO'.split()) Namespace(foo='FOO', x=None) 短选项可以写在一起: >>> parser.parse_args('-xX'.split()) Namespace(foo=None, x='X') parse_args()方法的返回值为namespace,可以用vars()内建函数化为字典: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'} # https://docs.python.org/2/library/functions.html#vars ''' #4.调试的tips ''' Argparse默认是从 sys.argv 中进行解析,但也可以直接解析字符串,如: values = parser.parse_args('--foo 1 -x 2 -y 3'.split()) 这在调试中很有用。 '''
更新一个较为通用的模板:
import argparse import sys def version_info(): VERSION_INFO = 'PROG v1' AUTHOR_INFO = 'Author: ixyzero.com' print VERSION_INFO print AUTHOR_INFO def scan(host, ports, threads, useragent): print host print ports print threads print useragent if __name__ == '__main__': parse = argparse.ArgumentParser() parse.add_argument('-v', '--version', action='store_true', default=False, help='Version information') parse.add_argument('-s', '--scan', action='store_true', default=False, help='Run masscan.') # parse.add_argument('-H', '--host', required=True, type=str, help='Scan this host or list of hosts') parse.add_argument('-H', '--host', type=str, help='Scan this host or list of hosts') parse.add_argument('-P', '--ports', type=str, default='21,22,80,443,8000,8080,8443,2080,2443,9090,6000,8888,50080,50443,5900', help='Specify ports in masscan format. (ie.0-1000 or 80,443...)') parse.add_argument('-t', '--threads', type=int, default=1, help='Specify the number of threads to use.') parse.add_argument('-a', '--ua', type=str, default='o_O O_o', help='Specify a User Agent for requests') args = parse.parse_args() if len(sys.argv) <= 1: parse.print_help() sys.exit(0) if args.version: #因为「action='store_true'」,所以「args.version的值为True/False」 version_info() sys.exit(0) if args.scan and (args.host is not None): #因为为args.host设置了「type=str」,所以「args.host的值为None/设定的字符串的值」 scan(args.host, args.ports, args.threads, args.ua)
=EOF=