python getopt
1.使用getopt模塊處理Unix模式的命令行選項:
getopt模塊用于抽出命令行選項和參數,也就是sys.argv。命令行選項使得程序的參數更加靈活。支持短選項模式和長選項模式。
e.g. python scriptname.py -f 'hello' --directory-prefix=/home -t --format 'a' 'b'import getoptshortargs = 'f:t'longargs = ['directory-prefix=', 'format', '--f_long=']opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )?getopt函數的格式是getopt.getopt ( [命令行參數列表], "短選項", [長選項列表] )
短選項名后的冒號(:)表示該選項必須有附加的參數。
長選項名后的等號(=)表示該選項必須有附加的參數。
返回opts和args。
opts是一個參數選項及其value的元組( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args是一個除去有用參數外其他的命令行輸入 ( 'a', 'b' )
然后遍歷opts便可以獲取所有的命令行選項及其對應參數了。
for opt, val in opts:if opt in ( '-f', '--f_long' ):passif ....???? 使用字典接受命令行的輸入,然后再傳送字典,可以使得命令行參數的接口更加健壯。
兩個來自python2.5 Documentation的例子:
?
>>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2']>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2']python Documentation中也給出了getopt的典型使用方法:
?
?下面一段程序演示了在getopt下使用Usage()函數、參數字典(默認參數)、短選項、長選項等。
?
2. 使用optparser模塊處理Unix模式的命令行選項:
optparser模塊非常的強大,完全體現了python的“如此簡單,如此強大”的特性。
import optparsedef getConfig(ini):import ConfigParsertry:cfg = ConfigParser.ConfigParser()cfg.readfp(open(ini))print cfg.sections()except:passif __name__=='__main__':parser = optparse.OptionParser()parser.add_option("-i","--ini",dest="ini",default="config.ini",help="read config from INI file",metavar="INI")parser.add_option("-f","--file",dest="filename",help="write report to FILE",metavar="FILE")parser.add_option("-q","--quiet",dest="verbose",action="store_false",default=True,help="don't print status messages to stdout")(options, args) = parser.parse_args()getConfig(options.ini)print args?another usage:
parser = OptionParser(usage='%prog [options] top_dir_name ')parser.disable_interspersed_args()parser.add_option('-t', '--top',dest='topdir', default=".",help='the top directory to search')parser.add_option('-o', '--output',dest='output', default="auto_search_result.txt",help='save the search result to output file')parser.add_option('-d', '--debug',action='store_true', dest='debug', default=False,help='enable debug output')(options, args) = parser.parse_args(sys.argv[1:])variable options.topdir receive the value of args after -t, so print options.topdir?
轉載于:https://www.cnblogs.com/lovemo1314/archive/2012/10/16/2725589.html
總結
以上是生活随笔為你收集整理的python getopt的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OC开发_整理笔记—— CoreLoca
- 下一篇: 戴尔服务器R740-iDRAC管理卡远程