Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set default values for SafeConfigParser?

Tags:

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.

like image 209
Martlark Avatar asked May 24 '11 07:05

Martlark


People also ask

What is config () in Python?

A Python configuration file is a pure Python file that populates a configuration object. This configuration object is a Config instance.

How do I use Configparser in Python?

Read and parse one configuration file, given as a file object. Read configuration from a given string. Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.

What is .ini file in Python?

An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties.


1 Answers

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') 
like image 182
Eli Bendersky Avatar answered Oct 06 '22 00:10

Eli Bendersky