#author("2018-05-26T13:10:08+09:00","default:mat2umoto","mat2umoto") #contents ***コマンドライン引数 [#k82907b2] argparseの使用例 #code(python){{ import argparse # ArgumentParserオブジェクトを生成する # descriptionにこのコマンドの説明を登録 parser = argparse.ArgumentParser(description='command description') # 位置引数(必須の引数) parser.add_argument('filepath', help='help message') # オプション引数は '--' を頭につける parser.add_argument('--a', help='help message') # デフォルト値 parser.add_argument('filepath', default='xxx.txt', help='help message') # 型を指定 parser.add_argument('num', type=int, default=10, help='help message') # 選択肢 parser.add_argument('lang', choices=('japanese', 'english'), help='help message') # 引数の文字の有無で区別する場合 # 通常は「--a 10」のように引数の後に値を書くが、この場合は「--a」を書くか否かに意味がある # この例は、書いた場合は1、省略した場合は0になる parser.add_argument('--a', action='store_const', default=0, const=1, help='help message') # 引数の文字の有無で区別する場合(True/False) # この例は、書いた場合はTrue、省略した場合はFalseになる parser.add_argument('--a', action='store_true', help='help message') # この例は、逆バージョン parser.add_argument('--a', action='store_false', help='help message') # コマンドライン引数の解析 args = parser.parse_args() }} 以降のプログラム中で、args.filepath、args.a のように引数にアクセスできる('--' は取り除かれる) ***リスト [#of69bdd7] ***タプル [#k46672b1] ***辞書 [#qc1e69af] ***文字コード [#rbe12521] ***文字列の書式指定 [#h6816594]