dak ブログ

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

python での yaml ファイルの読み込み

2021-09-19 23:34:02 | python
python での yaml ファイルの読み込み方法のメモ。

python で yaml を処理するためのライブラリの pyyaml をインストールします。
pip install pyyaml

以下のようにして pyyaml で yaml ファイルを読み込めます。
import sys
import yaml

def main():
    file = sys.argv[1]
    try:
        with open(file) as f:
            obj = yaml.safe_load(f)
            print(type(obj))
            print(obj)
    except:
        sys.stderr.write('error: failed to open %s\n' % (file))
        return 1

    return 0

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

上記のプログラムに以下の yaml ファイルを読み込ませてみます。
db:
  host: localhost
  port: 3306
  db:   test-user

vals1:
  - a
  - b
  - c

vals2: [a, b, c]

実行結果は以下のようになります。
'db': {'host': 'localhost', 'port': 3306, 'db': 'test-user'}, 'vals1': ['a', 'b', 'c'], 'vals2': ['a', 'b', 'c']}


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