pythondata-structuresdefaultdefault-valueconfigparser

How can I set default values for SafeConfigParser?


I have a config file as follows:

[job]
mailto=bob
logFile=blahDeBlah.txt

I want to read the options using SafeConfigParser:

values = {} 
config = ConfigParser.SafeConfigParser()
try:
    config.read(configFile)
    jobSection = 'job'

    values['mailto'] = config.get( jobSection, 'mailto' )
    values['logFile'] = config.get( jobSection, 'logFile' )
    # it is not there
    values['nothingThere'] = config.get( jobSection, 'nothingThere' )
.... # rest of code

The last line of course will throw an error. How can I specify a default value for the config.get() method?

Then again, if I have an options file as follows:

[job1]
mailto=bob
logFile=blahDeBlah.txt

[job2]
mailto=bob
logFile=blahDeBlah.txt

There seems to be no way to specify default options for job1 different from the default options in section job2.


Solution

  • You can also use a default ".ini" file and read it before your actual config file.

    default.ini:

    [job1]
    mailto=jack
    logfile=default.log
    
    [job2]
    mailto=john
    logfile=default.log
    

    config.ini:

    [job1]
    mailto=sparrow
    logfile=blah.log
    
    [job2]
    logfile=blah2.log
    

    parsing:

    import ConfigParser  # For Python 3 use the configparser module instead (all lowercase)
    
    config = ConfigParser.SafeConfigParser()
    config.read('default.ini')
    config.read('config.ini')
    
    print config.get('job1', 'mailto')
    # -> sparrow (from config.ini)
    
    print config.get('job1', 'logfile')
    # -> blah.log (from config.ini)
    
    print config.get('job2', 'mailto')
    # -> john (from default.ini)
    
    print config.get('job2', 'logfile')
    # -> blah2.log (from config.ini)