contents
getopt
- 引数はsys.argvに入ってくる.
- option引数の解析はgetopt.
- getopeの第二引数で、「:」が付くのは値をとる時.
- shortoptsの時は、引数が1文字の時.
-
lognoptsの時は、長い引数の時.
-
ex.) --help,--width 10のような時
getopt(args, shortopts, longopts=[])
-
ex.) --help,--width 10のような時
sample code
import getopt import sys try: optlist.args = getopt.getopt(sys.args[1:],"f:") except getopt.GetoptError,pe: print pe.msg sys.exit(0) for opt,args in optlist: if opt in ("-f"): print("ok")
optparse
- getoptより処理が楽
sample code
- infileには読み込むfile
- outfileには出力するfile
-
よくあるパターンのスクリプト
#! /bin/env python import outparse # getfile def getfiles(): usage = u'%prog [-f:infile] [-o:outfile] parser = optparse.OptionParser(usage=usage) parser.add_option( '-f','--infile', action='store', type='string', help=u'input text file', metavar='infile' ) parser.add_option( '-o','--outfile', action='store', type='string', help=u'output text file', metavar='outfile' ) options.args = parser.parse_args() # main if __name__ = '__main__' getfiles()
実行結果 1.
-
-hの引数でヘルプが出るのだ
[$/home/python] ./unko.py -h Usage: unko.py [-f:infile] [-o:outfile] Options: -h, --help show this help message and exit -f infile, --infile=infile infile text file -o outfile, --outfile=outfile outfile text file
実行結果 2.
-
-fオプションにちゃんと引数をつけるといいみたいだ
[$/home/python] ./unko.py -f unko [] {'outfile': None, 'infie': 'unko'}
実行結果 3.
-
-oもつけて完成
[$/home/python] ./unko.py -f unko -o test [] {'outfile':'test','infile':'unko'}