【发布时间】:2013-04-30 17:09:46
【问题描述】:
我正在创建当日服务器的报价。我正在从一个 INI 文件中读取选项,其文本如下:
[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()
为什么会出现此错误,我该如何解决?
【问题讨论】:
-
括号不起作用。使用
get()函数。configOptions.host = conifg.get('Server','host')docs.python.org/2/library/configparser.html#examples -
好吧,您尝试使用
config,就好像它是一本字典,但它不是,它是一个ConfigParser实例... -
以后,您可能想参考
ConfigParserdocumentation。 -
此解决方案适用于 py3
标签: python ini configparser