getoptモジュールを使用してコマンドラインオプションを処理する
1357 ワード
#!/usr/bin/env python
#-*- coding:utf8 -*-
import sys
import getopt
# getopt(args, shortopts, longopts=[])
"""
args sys.argv[1:]
shortopts (-)
longopts (--)
:
python test.py -i 127.0.0.1 -p 80 test
python test.py --ip=127.0.0.1 --port=80 test
"hp:i:"
:h ,p: i:
["help","ip=","port="]
:help =, ,ip port =,
options , [('-i','127.0.0.1'),('-p','80')]
args , '-' '--' , :['test']
: , '-' , '-'
"""
def usage():
print """
usage: python opt.py [option][value]...
-h, --help
-i, --ip=127.0.0.1 ip
-p, --port=80
"""
if __name__=='__main__':
try:
options, args = getopt.getopt(sys.argv[1:],"hp:i:",["help","ip=","port="])
except getopt.GetoptError:
sys.exit()
for name,value in options:
if name in ("-h","--help"):
usage()
if name in ("-i","--ip"):
print 'ip is',value
if name in ("-p","--port"):
print 'port is',value