コマンドラインオプションの処理をする : getopt

getopt はコマンドラインオプションのパーザのモジュールである。

参照
http://www.python.jp/doc/2.4/lib/module-getopt.html

記述の方法

o, a = getopt( args, options [, long_options ] )

引数

引数 説明
args コマンドライン引数。通常 sys.arg[ 1: ] を渡す。
options コマンドライン(ショート)オプションを示す文字列。
long_options (オプション項目) コマンドラインロングオプションの識別用のリスト。
オプションの書き方
optionsに入れる引数 データの処理
"abc" オプション -a, -b, -c を取得する。
"mn:" オプション -m, -n を取得する。オプション -n は引数を取る。

戻り値

2値のタプルが戻ります。

1つ目の要素は 「「「オプション と オプション引数」のタプル」のリスト」
2つ目の要素は 「オプション、及びオプション引数を取り去った後の引数のリスト」

例外

オプションの解析に失敗した場合は GetoptError の例外が発生します。

属性として msg と opt を持ちます。

例外パターン
  • 識別できないオプションが指定された。
  • 引数が必要なオプションに引数が与えられなかった
  • (ロングオプション時のみ) 不要なオプション引数を与えた

サンプルコード

getopt_sample.py

#!/usr/bin/env python
# coding : utf-8

import sys, getopt;

try:
    options, args = getopt.getopt( sys.argv[ 1: ], "abc:" );

    opt_dict = dict( options );

    for key in opt_dict.keys():
        if key == "-a":
            print "Hello, world!";
        elif key == "-b":
            print "Good bye!!";
        if key == "-c" :
            print opt_dict[ "-c" ];

    print "< end of program >";
except getopt.GetoptError, ge:
    print ge.msg, ge.opt;

動作テスト

$ python getoptsample.py
$ python getoptsample.py -a
$ python getoptsample.py -ab
$ python getoptsample.py -a -c
$ python getoptsample.py -b -c 11