Igor Igor - 1 year ago 525
Ini Question

Python - ConfigParser - AttributeError: ConfigParser instance has no attribute '__getitem__'

I am creating a quote of the day server. I am reading options from an INI file, whose text is below:

host =
port = 17


However, when I use ConfigParser, it gives me this error:

Traceback (most recent call last):
File "server.py", line 59, in <module>
File "server.py", line 55, in Start
configOptions = parseConfig(filename)
File "server.py", line 33, in parseConfig
server = config['Server']
AttributeError: ConfigParser instance has no attribute '__getitem__'

Here is my code:


from socket import *
from ConfigParser import *
import sys

class serverConf:
port = 17
host = ""
quotefile = ""

def initConfig(filename):

config = ConfigParser()

config['Server'] = {'port': '17', 'host': ''}
config['Quotes'] = {'file': 'quotes.txt'}

with open(filename, 'w') as configfile:

def parseConfig(filename):

configOptions = serverConf()

config = ConfigParser()

server = config['Server']

configOptions.port = int(server['port'])
configOptions.host = conifg['Server']['host']
configOptions.quoteFile = config['Quotes']['file']

print "[Info] Read configuration options"

return configOptions

def doInitMessage():

print "Quote Of The Day Server"
print "-----------------------"
print "Version 1.0 By Ian Duncan"
print ""

def Start():

filename = "qotdconf.ini"
configOptions = parseConfig(filename)

print "[Info] Will start server at: " + configOptions.host + ":" + configOptions.port


Why am I getting this error, and what can I do to fix it?

Answer Source

After a quick read it seems like you're trying to read the data as if it's a dictionary, when you should use: config.get(section, data)


config = ConfigParser()
configOptions.port = config.getint('Server', 'port')
configOptions.host = config.get('Server', 'host')
configOptions.quoteFile = config.get('Quotes', 'file')

To write to the config-file you could do something like:

def setValue(parser, sect, index, value):
    cfgfile = open(filename, 'w')
    parser.set(sect, index, value)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download