Python-ConfigParser-AttributeError:ConfigParser实例没有属性'__getitem__' [英] Python - ConfigParser - AttributeError: ConfigParser instance has no attribute '__getitem__'

查看:307
本文介绍了Python-ConfigParser-AttributeError:ConfigParser实例没有属性'__getitem__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建日间服务器的报价.我正在从INI文件中读取选项,该文件的文本如下:

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

但是,当我使用ConfigParser时,它给了我这个错误:

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__'

这是我的代码:

#!/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?

推荐答案

在快速阅读之后,您似乎应该像在用字典一样读取数据,何时应该使用:config.get(section, data)

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()

这篇关于Python-ConfigParser-AttributeError:ConfigParser实例没有属性'__getitem__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆