Python - ConfigParser - AttributeError:ConfigParser实例没有属性'__getitem__'
问题描述:
我正在创建一天报价服务器。我从一个INI文件,其文本阅读选项是以下:Python - ConfigParser - AttributeError:ConfigParser实例没有属性'__getitem__'
[Server]
host =
port = 17
[Quotes]
file=quotes.txt
然而,当我使用ConfigParser,它给了我这个错误:
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__'
这里是我的代码:
#!/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()
为什么我得到这个错误,我能做些什么来解决它?
答
快速阅读后,它看起来像你想读取数据,就好像它是一本字典,当你应该使用: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')
要写入config-文件,你可以这样做:
...
def setValue(parser, sect, index, value):
cfgfile = open(filename, 'w')
parser.set(sect, index, value)
parser.write(cfgfile)
cfgfile.close()
答
所包含ConfigParser
与Python 2.7不会以这种方式工作。但是,您可以使用后端端口configparser
模块available on PyPy准确实现您的建议。
pip install configparser
然后你可以使用它,就像你在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
注意
-
configparser
不使用Python 3版本兼容100%。 - backport旨在与Python 3.2+中的vanilla版本保持100%的兼容性。
- 以上述方式使用它,如果可用,将默认为Python 3实现。
括号不起作用。使用'get()'函数。 'configOptions.host = conifg.get('Server','host')' http://docs.python.org/2/library/configparser.html#examples – M456 2013-05-06 21:17:00
那么,你正在尝试使用'config'就好像它是一本字典,它不是,它是一个'ConfigParser'实例... – kindall 2013-05-06 21:19:30
未来,您可能想要引用['ConfigParser'文档](http://docs.python.org /2/library/configparser.html#configparser-objects)。 – 2013-05-06 21:23:57