views:

29

answers:

2

Hi All,

I have a config file FOO in /etc/sysconfig/. This Linux file is very similar to INI-File, but without a section declaration.

In order to retrieve a value from this file, I used to write a shell script like:

source /etc/sysconfig/FOO
echo $MY_VALUE

Now I want to do the same thing in python. I tried to use ConfigParser, but ConfigParser does not accept such an INI-File similar format, unless it has a section declaration.

Is there any way to retrieve value from such a file?

A: 

I suppose you could do exactly what you're doing with your shell script using the subprocess module and reading it's output. Use it with the shell option set to True.

Noufal Ibrahim
i finally use commands.getstatusoutput("source /etc/sysconfig/FOO;echo $BAR") to get values
stanleyxu2005
+1  A: 

If you want to use ConfigParser, you could do something like:

#! /usr/bin/env python2.6

from StringIO import StringIO
import ConfigParser

def read_configfile_without_sectiondeclaration(filename):
    buffer = StringIO()
    buffer.write("[main]\n")
    buffer.write(open(filename).read())
    buffer.seek(0)
    config = ConfigParser.ConfigParser()
    config.readfp(buffer)
    return config

if __name__ == "__main__":
    import sys
    config = read_configfile_without_sectiondeclaration(sys.argv[1])
    print config.items("main")

The code creates an in-memory filelike object containing a [main] section header and the contents of the specified file. ConfigParser then reads that filelike object.

codeape
ConfigParser has some problems. (1) All keys will be converted to lowercase. (2) The "" around a string value will not be removed. So finally I use another solution.
stanleyxu2005
Have a look at the ConfigObj library. Might be it handles the problems you mention. http://www.voidspace.org.uk/python/configobj.html
codeape