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
Python 3's configparser
module is much-improved and provides a get(option, default)
method.
Python 2's ConfigParser
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With