1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

引数処理(argparse)

Last updated at Posted at 2018-03-02

#注意点
引数が適切でない場合は、プログラムを勝手に終了させる。
なのでException処理ができない。ログに残す必要があるなどの場合は、optget使うしかないか・・・。

(2018/3/6 追記)
サブクラス化してargparse.ArgumentParser(super class)のエラーメソッドをオーバーライドすれば、プログラム終了を回避できる(以下訂正)。

py.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import sys

#error methodのオーバーライド
class ThrowingArgumentParser(argparse.ArgumentParser):
    def error(self, message):
        #エラーをロギング。loggerの設定は別記事参照
        logger.error('error occured while parsing args : '+ str(message))
        parser.print_help() 
        sys.exit(1)

import argparse # argparseモジュールをimport

helpmsg = """
This is help message.
You can set any messages here.
"""


parser = ThrowingArgumentParser(description=helpmsg)
parser.add_argument('-a','--application', # オプションを指定
                    help = "this is vm's registered ID",
                    # help表示時の引数の説明。囲むのは"でも'でもいい。
                    required = True,
                    # 引数の省略可否。boolean型
                    type = int,
                    # 型(str,longなど)を指定
                    choices = ['not','yet'], 
                    # 指定できる引数を[]内のものに限定
                    default = none 
                    # 引数未指定の場合のデフォルト値
                    action = 'store' 
                    # オプション指定時の動作指
                      ============================
                      store:普通に引数を取得して格納
                      const:constキーワード引数で指定された値を格納
                      store_true : オプションの指定あり=trueなし=falseを格納 
                      store_false : オプションの指定あり=falseなし=trueを格納
                      ============================
                    dest = 'SAMPLE'   # destを変数として値を格納
                    )
                    
args = parser.parse_args() 
#ここでsys.argvからの引数を実際に処理する。エラーハンドリングも内部でされるので、try文なしでOK。
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?