Help us understand the problem. What is going on with this article?

OptParserの使い方

More than 5 years have passed since last update.
#!/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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした