LoginSignup
3
4

More than 5 years have passed since last update.

OptParserの使い方

Last updated at Posted at 2013-09-25
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from optparse import OptionParser

if __name__ == '__main__':

    """ コマンドエラー時に表示する文字列 """
    usage = u'%prog [Args] [Options]\nDetailed options -h or --help'

    version = 0.1
    parser = OptionParser(usage=usage, version=version)

    """ test.py -d 20111201 のように、オプションの後に整数値を入力させたい場合 """
    parser.add_option(
        '-d', '--date',
        action = 'store',
        type = 'int',               # 受け取る値の型を指定する
        dest = 'download_date',     # 保存先変数名
        help = 'Set date(yyyymmdd) you want to download.(ex.20110811)'  # --help時に表示する文(見れば分かるかw)
    )

    """ 文字列が欲しい場合 (test.py -f hoge.txt) """
    parser.add_option(
        '-f', '--file',
        action = 'store',
        type = 'str',           # 型指定
        dest = 'file_name',     # 保存先変数名
        help = 'Set filename (ex. hoge.txt)'
    )

    """ -s を指定した場合、trueを保存する """
    parser.add_option(
        '-s', '--sleep',
        action = 'store_true',      # store_trueの場合、Trueが'dest'で指定された変数へ格納される。(false時はstore_false)
        dest = 'hoge_flg',
        help = 'set sleep flag'
    )

    """ 各オプションのデフォルト値をセット """
    parser.set_defaults(
        download_date = None,
        file_name = None,
        hoge_flg = False
    )

    """ オプションをパース """
    options, args = parser.parse_args()

    """ 単純な引数(例: test.py a b)はargs[index]で取得できる """
    if len(args) > 0:
        for i, v in enumerate(args):
            print 'Args[%s] is: %s' % (i, v)

    """ オプションで指定した値は options.<変数名>で取得できる """
    date = options.download_date
    if date:
        if len(str(date)) != 8:
            # エラーを発生させるときは↓こんな感じ
            parser.error('Date must be yyyymmdd')

    print 'date: %s, file: %s, sleep: %s' % (options.download_date, options.file_name, options.hoge_flg)

このファイルを –help オプションをつけて実行すると

$ python test.py --help

Usage: test.py [Args] [Options]
Detailed options -h or --help

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -d DOWNLOAD_DATE, --date=DOWNLOAD_DATE
                        Set date(yyyymmdd) you want to download.(ex.20110811)
  -f FILE_NAME, --file=FILE_NAME
                        Set filename (ex. hoge.txt)
  -s, --sleep           set sleep flag
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4