开发者

How can I set default values for SafeConfigParser?

I have a config file as follows:

[job]开发者_如何学Go
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.


Use the defaults parameter to the constructor:

# class ConfigParser.SafeConfigParser([defaults[, dict_type]]) 
#
config = ConfigParser.SafeConfigParser({'nothingThere': 'lalalalala'})
...
...
# If the job section has no "nothingThere", "lalalalala" will be returned
# 
config.get(jobSection, 'nothingThere')


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:

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)


In Python 3 you can provide a fallback value to the get() method as follows:

values['nothingThere'] = config.get('job', 'nothingThere', fallback=0)
print(values['nothingThere'])
# -> 0


You can use the [DEFAULT] section to set default values for the properties you haven't defined in any other section(s).

E.g.

[DEFAULT]
checkout_root: /data/workspace

[pingpong]
name: Ping Pong App
checkout_root: /home/pingpong
src: %(checkout_root)s/src

[dingdong]
name: Ding Dong App
src: %(checkout_root)s/dingdong_src

For the ding ding app, the value of src will be /data/workspace/dingdong_src

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜