[Python]configparserを使用して設定ファイルの値を使用する

定数となる値を別ファイルで使用したい場合にconfigparserを使用している。
使い方の簡単なメモ。

定数をまとめたconfig.ini。

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

別プログラムで上記の設定ファイルを読み込む。

import configparser

config = configparser.ConfigParser()
config.sections()

config.read('./config.ini')
print(config.sections())
# => ['bitbucket.org', 'topsecret.server.com']

print(config['DEFAULT']['ServerAliveInterval'])
# => 45

という使い方になる。
また今回はcronスクリプト内で使用していたが、cronの時にはファイルの読み込み時に少し工夫が必要になる。
下記のページに記載があった。

config.read(os.path.join(os.path.dirname(__file__), 'config.ini'))

参考

configparser — 設定ファイルのパーサー

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

nineteen − 17 =

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください