コマンドラインオプションの解析
from optparse import OptionParser, OptionValueError import os # スクリプトの使用方法を表す文字列 # デフォルト値は"Usage: %prog [options]" # "usage: "で始まらないと自動的に"usage :"が追加される # %progはスクリプト名で置換 usage = "usage: %prog [options] keyword" # OptionPraserのインスタンスを生成 parser = OptionParser(usage) # オプションの追加 # action オプションが見つかった場合に行う処理 # type オプションの型 # dest 引数の保存先 # 省略時は長いオプション名を使用 # それも省略なら短いオプション名 # default オプションのデフォルト値 # 省略した場合のデフォルト値はNone # metavar ヘルプ表示で使われる仮引数 # 省略時は保存先の名前を大文字にして使用 parser.add_option( "-f", "--file", # どちらか一つは必ず必要 action="store", # 引数を保存(デフォルト値) type="string", # 引数をそのまま文字列として保存(デフォルト値) dest="log_file", help="log file" ) parser.add_option( "-l", "--line", type="int", # 引数をint( )で変換して保存 metavar="N", default=10, help="display search result up to N" ) parser.add_option( "-s", type="choice", # 引数がchoicesに含まれていなければエラー choices=["Yahoo", "Google", "Wikipedia"], default="Yahoo", metavar="SEARCH ENGINE", help="choose search engine form Yahoo, Google, Wikipedia" ) parser.add_option( "-x", action="append_const", # constで指定した定数を追加 const="X", dest="hoge", default=[], # この場合はリストでなければエラー # デフォルト値に[]を指定しなくても、オプションが # 見つかった時点で保存先は[]で初期化される help="meaningless option" ) parser.add_option( "-y", action="append_const", const="Y", dest="hoge", help="meaningless option" ) parser.add_option( "-d", "--debug", action="store_true", # Trueを保存 # store_falseならFalseを保存 default=False, help="debug" ) def check_directory(option, opt_str, value, parser): if os.path.isdir(value): parser.values.dir = value # オプションの引数を保存 else: raise OptionValueError("option -dir: %s is not directory" % value) parser.add_option( "--dir", action="callback", # callbackで指定した関数を呼び出す callback=check_directory, type="string", # 引数を取るなら必須 default="./", dest="dir", help="direcotry to hogehoge" ) # コマンドラインの解析 # options 全てのオプションの値が入ったオブジェクト # args コマンドライン解析後に残った引数 (options, args) = parser.parse_args() # エラー処理 if not args: # エラーメッセージを表示し、プログラムを終了 parser.error("requires keyword") #parser.print_help() # ヘルプメッセージを表示 #exit() # プログラムを終了 # オプションを参照 # dest="file"ならoptions.fileで参照 # destが省略されていれば長いオプション名で参照 # それも省略されていれば短いオプション名で参照 print "options.log_file =", options.log_file print "options.line =", options.line print "options.s =", options.s print "options.hoge =", options.hoge print "options.debug =", options.debug print "options.dir =", options.dir print "keyword =", args[0]
$ test.py -h Usage: test.py [options] keyword Options: -h, --help show this help message and exit -f LOG_FILE, --file=LOG_FILE log file -l N, --line=N display search result up to N -s SEARCH ENGINE choose search engine form Yahoo, Google, Wikipedia -x meaningless option -y meaningless option -d, --debug debug --dir=DIR direcotry to hogehoge $ test.py python options.log_file = None options.line = 10 options.s = Yahoo options.hoge = [] options.debug = False options.dir = ./ keyword = python $ test.py python -f hoge.txt -l 20 -s Google -x -y -d --dir hoge options.log_file = hoge.txt options.line = 20 options.s = Google options.hoge = ['X', 'Y'] options.debug = True options.dir = hoge keyword = python $ test.py Usage: test.py [options] keyword test.py: error: requires keyword $ test.py python -f Usage: test.py [options] keyword test.py: error: -f option requires an argument $ test.py python -l 20x Usage: test.py [options] keyword test.py: error: option -l: invalid integer value: '20x' $ test.py python -s Goo Usage: test.py [options] keyword test.py: error: option -s: invalid choice: 'Goo' (choose from 'Yahoo', 'Google', 'Wikipedia') $ test.py python --dir hogehoge Usage: test.py [options] keyword test.py: error: option -dir: hogehoge is not directory
詳しくはoptparserのマニュアルを参照してください。