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

标签 python ini configparser

我正在创建每日报价服务器。我正在阅读 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()

为什么会出现此错误,我该如何解决?

最佳答案

快速阅读后,您似乎正在尝试将数据当作字典来读取,此时您应该使用:config.get(section, data)

如:

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

要写入配置文件,您可以执行以下操作:

...
def setValue(parser, sect, index, value):
    cfgfile = open(filename, 'w')
    parser.set(sect, index, value)
    parser.write(cfgfile)
    cfgfile.close()

关于Python-ConfigParser-AttributeError : ConfigParser instance has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16407329/

相关文章:

python - ConfigParser 和带值但不带键的部分

python - Python中跨模块和静态方法访问全局变量

Python正则表达式提取两个特殊字符之间的正数和负数

c# - 如何更新特定部分中的特定ini键?

c++ - 如何在 OS X 上使用 QSettings 存储 INI 文件

python - Revit.ini 文件 - MissingSectionHeaderError : File contains no section headers. 文件 : Revit. ini,行:1 '\xff\xfe\r\x00\n'

python - 如何从配置文件中删除白色字符?

python - 为什么 print 2++3 在 python 中打印 5?

python 美汤 : How to extract text next to a tag?

PHP ini file_get_contents 外部网址