Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 977
Dave Avatar asked Mar 13 '23 01:03

Dave


1 Answers

Python 3's configparser module is much-improved and provides a get(option, default) method.

Python 2's ConfigParsers allow for a DEFAULT section (supplied at construction time) although in that case you would have to know the defaults for each option ahead of time.

If you are on Python 2 and need to provide a default at the call site, sub-classing per Rob's answer seems like the way to go.

like image 196
Sam Brightman Avatar answered Apr 29 '23 17:04

Sam Brightman