0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i finally use commands.getstatusoutput("source /etc/sysconfig/FOO;echo $BAR") to get values
1

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.

2 Comments

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.
Have a look at the ConfigObj library. Might be it handles the problems you mention. voidspace.org.uk/python/configobj.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.