We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,344 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Reading properties file in Python, except using ConfigParser()

How to read properties file in Python? I found ConfigParser() but it has a 'section' limitation, so looking for other alternatives.

Thanks,

Harsh

3
Contributors
10
Replies
2 Weeks
Discussion Span
7 Months Ago
Last Updated
11
Views
Question
Answered
hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

You could add a 'mock section' and still use ConfigParser

# tested with python 2.7.2
import ConfigParser
from functools import partial
from itertools import chain

class Helper:
    def __init__(self, section, file):
        self.readline = partial(next, chain(("[{0}]\n".format(section),), file, ("",)))

config = ConfigParser.RawConfigParser(allow_no_value=True)
with open("essconfig.cfg") as ifh:
    config.readfp(Helper("Foo", ifh))
print(config.get("Foo", "old_passwords"))

The config file was

user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb
skip-innodb
Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11
Question Answered as of 7 Months Ago by Gribouillis

You are a lifesaver; it worked like a charm.

Thanks again,

Harsh

hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

sorry to bother you again but apparently, functools and itertools modules are not there in python 2.2.1. Can you give another version of your program that is compatible with 2.2.1?

hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This class should work for very old versions of python

class Helper:
    def __init__(self, section, file):
        self.section = "[%s]\n" % section
        self.file = file
        self.state = -1

    def readline(self):
        if self.state:
            if self.state < 0:
                self.state = 0
                return self.section
            else:
                return ""
        else:
            s = self.file.readline()
            if not s:
                self.state = 1
            return s

Why don't you upgrade ? Python 2.2 is a dinosaur :)

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

Thanks for your quick revert. Much as I'd like to upgrade, this python version is embedded in another product and I've to live with this :(

BTW, can you confirm if below code snippet would also work as it is with older python versions or it merits further changes? I'm getting invalid syntax error here, but seems to be misleading to me.

with open("essconfig.cfg") as ifh:
config.readfp(Helper("Foo", ifh))

hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Try

try:
    ifh = open("essconfig.cfg", "rb")
    config.readfp(Helper("Foo", ifh))
finally:
    ifh.close()

but I don't know how configparser was in python 2.2.1

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

Thank-You! seems to be working at first glance.

BTW, would you recommend using stringIO to achieve the same?

hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

BTW, would you recommend using stringIO to achieve the same?

Given that configuration files are often small files, I would say why not ? Loading a small file in memory is not a very expensive operation.

Gribouillis
Posting Maven
Moderator
3,101 posts since Jul 2008
Reputation Points: 1,130
Solved Threads: 761
Skill Endorsements: 11

I see you have get good help from Gribouillis.
As a note with open was new in python 2.5.
python 2.2.1 is really old.
Alternatives is to write your own parser that works for your files,it`s not so hard.
If i use config file postet by Grib.

cfg_dict = {}
lst = []
cfg_file = open('essconfig.cfg')
for line in cfg_file:
    if '-' and not '=' in  line:
        line = line.split()
        line.append('None')
        lst.append( line)
    else:
        line = ''.join(line.strip().split('=')).split()
        lst.append(line)
cfg_file.close()

for item in lst:
    cfg_dict[item[0]] = item[1]
print cfg_dict

Test it.

>>> cfg_dict['old_passwords']
'1'
>>> cfg_dict['pid-file']
'/var/run/mysqld/mysqld.pid'
>>> cfg_dict['skip-bdb']
'None'
>>> cfg_dict['user']
'mysql'
snippsat
Posting Shark
957 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

Dear Snippsat,

Thanks for responding. For now, my issue is resolvedb by using Gribouillis' suggestions; nevertheless, look forward to continued help from Python gurus on this forum.

Regards,

Harsh

hpoddar
Newbie Poster
6 posts since Oct 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.1053 seconds using 2.67MB