1

I am trying to read a property from properties file and if it is not there, i need to add that property to properties file

Following is my script

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('test.properties')

ip = config.get('client', 'primaryIp')
print "ip is " +ip

if not ip:
    Config.set('client','primaryIp','10.31.1.143')

But it throws the following error at line " ip = config.get('client', 'primaryIp') "

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    ip = config.get('client', 'primaryIp')
  File "/usr/lib64/python2.7/ConfigParser.py", line 340, in get
    raise NoOptionError(option, section)
ConfigParser.NoOptionError: No option 'primaryIp' in section: 'client'

How could i avoid this exception

1 Answer 1

2

Use try except to catch you exception if there is any.

It's a simple concept if you have the option primaryIp then everything is ok, but if you have an NoOptionError then you need to set the option since it's not present in the file:

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('test.properties')

try:
    ip = config.get('client', 'primaryIp')
    print "ip is " +ip
except NoOptionError:
    config.set('client','primaryIp','10.31.1.143')
Sign up to request clarification or add additional context in comments.

3 Comments

Executing the above script throws the following exception,Traceback (most recent call last): File "test.py", line 9, in <module> except NoOptionError: NameError: name 'NoOptionError' is not defined
When i modified it to except ConfigParser.NoOptionError:, it executed successfully, but primaryIp property is not written to test.properties
You fix is current or you can from ConfigParser import NoOptionError, as for the set you need to write it to the file from the config object with something like config.write(configfile)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.