LoginSignup
22
26

More than 5 years have passed since last update.

[Python] iniファイルに変数を埋め込む方法

Last updated at Posted at 2018-08-01

概要

以下の2つを、SafeConfigParserを使って実現します。

  1. iniファイルに変数を埋め込む方法
  2. iniファイルを動的に生成する

iniファイルに変数を埋め込む方法

iniファイルを作成

以下のいずれかの書式で作成。
%(変数名)の形式で変数を実装する。

sample.ini
[general]
name: my_name
base_dir: /home/myhome/exp

exe_dir: %(base_dir)s/bin
sample.ini
[general]
name=my_name
base_dir=/home/myhome/exp

exe_dir=%(base_dir)s/bin

コードを作成

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

config = configparser.SafeConfigParser()
config.read('sample.ini')
value = config.get('general', 'exe_dir')

print(value)

実行

$ python sample.py
/home/myhome/exp/bin

iniファイルを動的に生成する

以下の方法でiniファイルを動的に生成することで、環境変数やその他の処理を自由に行うことができる。
ここでは、環境変数ENVに値を設定して、それを用いてiniファイルを生成してみる。

環境変数のセット

$ export ENV=development

iniファイルを生成するスクリプトの作成

generate.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import ConfigParser
import os

config = ConfigParser.RawConfigParser()

section1 = 'general'
config.add_section(section1)
config.set(section1, 'env', os.environ.get('ENV'))
config.set(section1, 'name', 'myname')
config.set(section1, 'base_dir', '/home/myhome/exp')
config.set(section1, 'exe_dir', '%(base_dir)s/bin')
config.set(section1, 'hostname', '%(env).hostname')

with open('sample.ini', 'wb') as configfile:
    config.write(configfile)

このコードを実行すると、以下のiniファイルが生成される。
環境変数によって、envの値を変えることができる。

sample.ini
[general]
env = development
name = myname
base_dir = /home/myhome/exp
exe_dir = %(base_dir)s/bin
hostname = %(env).hostname

参考

22
26
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
22
26