python的命令解析getopt.getopt()函数分析
生活随笔
收集整理的這篇文章主要介紹了
python的命令解析getopt.getopt()函数分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【轉自http://hi.baidu.com/javalang/blog/category/Python】
可以參考http://docs.python.org/lib/module-getopt.html
?
# -*- coding: cp936 -*-import getopt
import sys
def usage():
??? print '''Help Information:
??? -h: Show help information
??? -xValue:
??? ...'''
if __name__=='__main__':
??? #set default values
??? x=1
??? y='y'
??? try:
??????? print sys.argv[1:]
??????? opts,args=getopt.getopt(sys.argv[1:],'hx:y:d')
??????? #opts 是帶-選項的參數
??????? #args 是沒有選項的參數
??????? print opts
??????? print args
??????? #h表示使用-h,h選項沒有對應的值
??????? #x:表示你要使用-xValue,x選項必須有對應的值.
??? except getopt.GetoptError:
??????? #打印幫助信息并退出
??????? usage()
??????? sys.exit(2)
??? #處理命令行參數
??? for o,a in opts:
??????? if o=='-h':
??????????? usage()
??????????? sys.exit()
??????? if o=='-x':
??????????? try:
??????????????? x=x+int(a) #注意默認a為字符串
??????????? except ValueError:
??????????????? print 'Invalid Value'
??????????? print x
??????? if o=='-d':
??????????? print 'use -d'
??????? if o=='-y':
??????????? y=y+a
運行結果:
getopt_example.py -x12 -y ss -d sdf s123
['-x12', '-y', 'ss', '-d', 'sdf', 's123']
[('-x', '12'), ('-y', 'ss'), ('-d', '')]
['sdf', 's123']
13
use -d
總結
以上是生活随笔為你收集整理的python的命令解析getopt.getopt()函数分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 再议libcurl编程
- 下一篇: 推荐系统(5)-深度推荐模型-AutoR