How to make a ConfigParser return a default value instead of raising a NoOptionError?

Viewed 6189

I have a config file with some options defined. Sometimes, if the requested option is not found, I want to ignore the error and return None.

setting.cfg:

[Set]
ip=some_ip
verify=yes     #if verify does not exist here --> verify=None

test.py:

import sys
import ConfigParser

file="setting.cfg"

class ReadFile:
   def read_cfg_file(self):
      configParser = ConfigParser.RawConfigParser(allow_no_value=True)
      if os.path.isfile(file):
          configParser.read(file)
      else:
          sys.exit(1)
      try:
          verify = configParser.get('Set', 'verify')
      except ConfigParser.NoOptionError:
          pass

      return verify,and,lots,of,other,values

If I handle it like this, I can't return values, as it simply passes if the 'verify' option is not found.

Is there any way I can ignore errors if an option is not found, and instead return None?

For example, something like this:

verify = configParser.get('Set', 'verify')
if not verify:
    verify=False
3 Answers

Python 2.7.12

You can take advantage of the ConfigParser() class get() method, which allows you to specify a defaults dictionary when called:

$ cat myconf.txt
[files]
path1 = /tmp
path2 = /usr/bin
path3 =

$ ipython
...
In [1]: import ConfigParser
   ...: 
   ...: cp = ConfigParser.ConfigParser(allow_no_value=True)
   ...: cp.read('myconf.txt')
   ...: defaults = { 'path4' : '/opt/include'}
   ...: print 'path1:', cp.get('files', 'path1', 0, defaults)
   ...: print 'path3:', cp.get('files', 'path3', 0, defaults)
   ...: print 'path4:', cp.get('files', 'path4', 0, defaults)
   ...: 
path1: /tmp
path3: 
path4: /opt/include
Related