It is a method to read the INI file as an example of loading the settings that went out with Ruby and Python.
Python 2.7.5 Ruby 1.9.3
The INI file to be read looks like this. "Hoge3" is not described in "TEST2" so that you can see the behavior when there is no key name.
test.ini
[TEST1]
hoge1=aaa
hoge2=bbb
hoge3=ccc
hoge4=ddd
[TEST2]
hoge1=AAA
hoge2=BBB
hoge4=CCC
Python First, let Python load the configuration file. Python uses the standard "ConfigParser" module. The execution environment is 2.7, but this area should be almost the same even in 3 series. .. ..
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
If there is no key name, it seems to throw an error.
Ruby Then do the same in Ruby. The execution environment is 1.9.3. In the case of Ruby, you need to install the "inifile module" first. To install, just execute the following gem command.
gem install inifile
And the source code.
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
In the case of ruby, it seems that an empty string is returned when there is no key name.
Python Module is provided as standard Throw an error when there is no key name
Ruby Requires installation If there is no key name, an empty string will be returned and no error will occur.
It seems that the application is better if you do not throw an error even if you do not have a key name, I'm happy with the standard if it's an environment where you can't install it freely.
Recommended Posts