getopt --- C 形式のコマンドラインオプション解析¶
ソースコード: Lib/getopt.py
注釈
このモジュールは機能が完成したものとされています。
この API より宣言的で拡張しやすい代替手段として、optparse モジュールがあります。
コマンドライン引数処理のさらなる機能拡張は、PyPI のサードパーティーモジュールか、argparse モジュールの機能として提供されます。
このモジュールは、スクリプトで sys.argv のコマンドライン引数を解析する際に役立ちます。
Unix の getopt() 関数と同じ規則をサポートします (引数 "-" と "--" の特別な意味も含みます)。
省略可能な第 3 引数により、GNU ソフトウェアがサポートするものと同様の長形式のオプションも使えます。
Unix の getopt() 関数に不慣れな場合は、代わりに argparse モジュールの使用を検討してください。
Unix の getopt() 関数に慣れていて、同等の動作をより少ないコードで実現し、より適切なヘルプやエラーメッセージを得たい場合は、optparse モジュールの使用を検討してください。
詳しくは 引数解析ライブラリの選択 を参照してください。
このモジュールは2つの関数と1つの例外を提供しています:
- getopt.getopt(args, shortopts, longopts=[])¶
Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means
sys.argv[1:]. shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'; i.e., the same format that Unixgetopt()uses).注釈
GNU の
getopt()とは異なり、オプションでない引数が現れると、それ以降のすべての引数もオプションではないものとして扱います。 これは GNU 以外の Unix システムと同様の動作です。longopts, if specified, must be a list of strings with the names of the long options which should be supported. The leading
'--'characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='). Optional arguments are not supported. To accept only long options, shortopts should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if longopts is['foo', 'frob'], the option--fowill match as--foo, but--fwill not match uniquely, soGetoptErrorwill be raised.If longopts is a string it gets treated as a list of a single element.
返り値は2つの要素から成っています: 最初は
(option, value)のタプルのリスト、2つ目はオプションリストを取り除いたあとに残ったプログラムの引数リストです (args の末尾部分のスライスになります)。それぞれの引数と値のタプルの最初の要素は、短形式の時はハイフン 1つで始まる文字列 (例:'-x')、長形式の時はハイフン2つで始まる文字列 (例:'--long-option') となり、引数が2番目の要素になります。引数をとらない場合には空文字列が入ります。オプションは見つかった順に並んでいて、複数回同じオプションを指定できます。長形式と短形式のオプションは混在できます。
- getopt.gnu_getopt(args, shortopts, longopts=[])¶
この関数はデフォルトで GNU スタイルのスキャンモードを使う以外は
getopt()と同じように動作します。つまり、オプションとオプションでない引数とを混在させることができます。getopt()関数はオプションでない引数を見つけると解析を停止します。オプション文字列の最初の文字が
'+'の場合、または環境変数POSIXLY_CORRECTが設定されている場合は、オプションでない引数が現れた時点でオプションの処理を停止します。
- exception getopt.GetoptError¶
引数リストに認識できないオプションがある場合、または必須の引数がオプションに指定されていない場合に送出されます。 例外の引数はエラーの原因を示す文字列です。 長形式のオプションでは、引数を取らないオプションに引数が指定された場合もこの例外を送出します。
msgとopt属性は、それぞれエラーメッセージと関連するオプションを表します。 エラーに関連する特定のオプションがなければ、optは空文字列です。
- exception getopt.error¶
GetoptErrorへのエイリアスです。後方互換性のために残されています。
Unix スタイルのオプションを使った例です:
>>> 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']
スクリプトでの典型的な使用例は次のようになります。
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# ヘルプ情報を表示して終了する:
print(err) # "option -a not recognized" などと表示する
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
process(args, output=output, verbose=verbose)
if __name__ == "__main__":
main()
optparse モジュールを使うと、同等のコマンドラインインターフェースをより少ないコードで作成でき、ヘルプやエラーメッセージもより詳しくなります。
import optparse
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-o', '--output')
parser.add_option('-v', dest='verbose', action='store_true')
opts, args = parser.parse_args()
process(args, output=opts.output, verbose=opts.verbose)
この場合は argparse モジュールを使っても、ほぼ同等のコマンドラインインターフェースを作成できます。
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
parser.add_argument('rest', nargs='*')
args = parser.parse_args()
process(args.rest, output=args.output, verbose=args.verbose)
このコードの argparse 版と optparse (および getopt) 版の動作の違いについては、引数解析ライブラリの選択 を参照してください。