dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

python でのコマンドライン引数の取得

2021-09-19 23:19:41 | python
python でのコマンドライン引数の取得方法のメモ。

python でコマンドライン引数を取得するライブラリの OptionParser の使用例。
import sys
import os
from optparse import OptionParser

def get_opts():
    param = {
        'opts': None,
        'args': None,
    }
    
    try:
        optp = OptionParser()
        optp.add_option('-c', dest='config')
        optp.add_option('-i', dest='input')
        optp.add_option('-o', dest='output')
        (opts, args) = optp.parse_args()
        param['opts'] = opts
        param['args'] = args
    except:
        return None

    return param
    
def main():
    param = get_opts()
    if param is None:
        return 1
    
    print(param)
    return 0

if __name__ == '__main__':
    res = main()
    exit(res)


実行例:
$ python3 test1.py -c config.yaml -i input.txt -o output.txt arg1.txt arg2.txt
{'opts': <Values at 0x7fb0dbbe5b70: {'config': 'config.yaml', 'input': 'input.txt', 'output': 'output.txt'}>, 'args': ['arg1.txt', 'arg2.txt']}

-o を指定しない場合には output が None となります。
$ python3 test1.py -c config.yaml -i input.txt arg1.txt
{'opts': <Values at 0x7f1dd27e7b38: {'config': 'config.yaml', 'input': 'input.txt', 'output': None}>, 'args': ['arg1.txt']}

不要なオプション(-e)を指定するとエラーになります。
 python3 test1.py -c config.yaml -i input.txt -o output.txt -e else.txt arg1.txt arg2.txt
Usage: test1.py [options]

test1.py: error: no such option: -e


この記事についてブログを書く
« JavaScript で数値を桁数指定... | トップ | python での yaml ファイルの... »

python」カテゴリの最新記事