更详细的可以参考官方文档:https://docs.python.org/2/library/optparse.html
快速入门参考这篇文章:https://www.jianshu.com/p/bec089061742
[root@shuffle-dev py_test]$ vim parse.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import OptionParser
if __name__ == '__main__':
usage=("Usage: python parse.py --name --password")
parser=OptionParser(usage=usage)
parser.add_option("--name",action="store",dest="name",metavar="NAME",help="name eg:shuffle")
parser.add_option("--password",action="store",dest="pwd",metavar="PASSWORD",help="password eg:123")
(options,args)=parser.parse_args()
print options,args
if not (options.name and options.pwd):
parser.error("specify --name --password")
name=options.name
pwd=options.pwd
print name,pwd
[root@shuffle-dev py_test]$ ./parse.py -h
Usage: python parse.py --name --password
Options:
-h, --help show this help message and exit
--name=NAME name eg:shuffle
--password=PASSWORD password eg:123
[root@shuffle-dev py_test]$ ./parse.py
{'pwd': None, 'name': None} []
Usage: python parse.py --name --password
parse.py: error: specify --name --password
[root@shuffle-dev py_test]$ ./parse.py --name shuffle --password 123
{'pwd': '123', 'name': 'shuffle'} []
shuffle 123