I am creating a quote of the day server. I am reading options from an INI file, whose text is below:
[Server]
host =
port = 17
[Quotes]
file=quotes.txt
However, when I use ConfigParser, it gives me this error:
Traceback (most recent call last):
File "server.py", line 59, in <module>
Start()
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:
#!/usr/bin/python
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:
config.write(configfile)
def parseConfig(filename):
configOptions = serverConf()
config = ConfigParser()
config.read(filename)
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
Start()
Why am I getting this error, and what can I do to fix it?
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)
EG:
...
config = ConfigParser()
config.read(filename)
...
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)
parser.write(cfgfile)
cfgfile.close()
The included ConfigParser
with python 2.7 does not work in this fashion. You can, however, achieve exactly what you've proposed using the back ported configparser
module available on PyPy.
pip install configparser
Then you can use it just as you would in Python 3*
from configparser import ConfigParser
parser = ConfigParser()
parser.read("settings.ini")
# or parser.read_file(open("settings.ini"))
parser['Server']['port']
# '17'
parser.getint('Server', 'port')
# 17
NOTE
configparser
is not 100% compatible with the Python 3 version. 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