LoginSignup
22
31

More than 5 years have passed since last update.

PythonやRubyでのINIファイルの参照

Last updated at Posted at 2014-09-21

はじめに

RubyとPythonで外出しした設定を読み込ませる一例としてINIファイルを読ませる方法です。

実行環境

Python 2.7.5
Ruby 1.9.3

INIファイル

読み込ませるINIファイルはこんな感じです。
key名がない場合の挙動もみれるよう「TEST2」では「hoge3」を記述しません。

test.ini
[TEST1]
hoge1=aaa
hoge2=bbb
hoge3=ccc
hoge4=ddd

[TEST2]
hoge1=AAA
hoge2=BBB
hoge4=CCC

Python

まずPythonで設定ファイルを読み込ませます。
Pythonは標準である「ConfigParser」モジュールを使用します。
実行環境は2.7ですが3系でもこの辺はほとんど同じはず。。。

readSetting.py


import ConfigParser

def _get(inifile, section, name):
    try:
        return inifile.get(section, name)
    except Exception, e:
        return "error: could not read " + name

if __name__=="__main__":

    inifile = ConfigParser.SafeConfigParser()
    inifile.read("./test.ini")

    for section in inifile.sections():
        print '===' + section + '==='
        print _get(inifile, section, "hoge1")
        print _get(inifile, section, "hoge2")
        print _get(inifile, section, "hoge3")
        print _get(inifile, section, "hoge4")

結果
===TEST1===
aaa
bbb
ccc
ddd
===TEST2===
AAA
BBB
error: could not read hoge3
CCC

key名が無い場合、エラーを吐くようです。
※ちなみに吐かれるエラーは「ConfigParserNoOptionError

Ruby

続いてRubyで同じことをします。
実行環境は1.9.3です。
Rubyの場合はまず、「inifileモジュール」のインストールが必要になります。
インストールは下記gemコマンドを実行するだけです。

gem install inifile

そしてソースコードです。

readSetting.rb

require 'inifile'

def _get(inifile, section, name)
  begin
    return inifile[section][name]
  rescue => e
    return "error: could not read #{name}"
  end
end

inifile = IniFile.load('./test.ini')

inifile.each_section do |section|
  puts "===#{section}==="
  puts _get(inifile, section, 'hoge1')
  puts _get(inifile, section, 'hoge2')
  puts _get(inifile, section, 'hoge3')
  puts _get(inifile, section, 'hoge4')
end
結果
===TEST1===
aaa
bbb
ccc
ddd
===TEST2===
AAA
BBB

CCC

rubyの場合はkey名が無い時、空文字が返ってくるようです。

まとめ

Python

モジュールが標準で備わっている
key名が無い時にエラーを吐く

Ruby

インストールが必要
key名が無い時は空文字が返ってくるだけでエラーにはならない

ちょっとだけ感想

key名がなくてもエラーを吐かない方が応用は利きそうだが、
自由にインストールとかできない環境だと標準の方が嬉しいですね。

22
31
2

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
31