Python - ConfigParser - AttributeError: ConfigParser实例没有'__getitem__'属性。

9

我正在创建一个每日引用服务器。我正在从一个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()

为什么我会遇到这个错误,该怎样修复它?

1
括号无法使用。请使用get()函数。configOptions.host = config.get('Server', 'host')http://docs.python.org/2/library/configparser.html#examples - M456
你试图将 config 当作字典来使用,但它不是,它是一个 ConfigParser 实例... - kindall
将来,您可能需要参考ConfigParser文档 - Martijn Pieters
1
这个解决方案适用于Python 3。 - Tommy
3个回答

14

经过快速阅读,似乎您试图将数据读取为字典,而您应该使用: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()

我一定是在某个网站上误读了指南,因为我以为它说要使用尖括号。 - Igor
你可以使用Python文档: http://docs.python.org/2/library/configparser.html - b0bz
16
这是Python 3版本的configparser和Python 2.7版本的configparser之间的区别。在Python 3.3中,以下是通常的操作方法。 - chiffa
这真的很烦人,因为它们的名称几乎完全相同。我的本地Python2找到了configparser并且没有任何问题地使用它,但它导致了我的暂存区崩溃,这让我花了一些时间才想出将其重命名为ConfigParser并且不使用尖括号。 感谢stackoverflow的帮助! - c8999c 3f964f64

5

Python 2.7 自带的 ConfigParser 无法按照您所需的方式工作。但是,您可以使用后移植的 configparser 模块(可在 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 版本不完全兼容。
  • 这个补丁旨在保持与 Python 3.2+ 中原始版本的100%兼容性。
  • 按照上面的方式使用它,如果可用的话,默认会使用 Python 3 实现。

0

适用于Python3
iniparser.py

#!/usr/bin/python3
import configparser
import sys

config = configparser.ConfigParser()
config.read(sys.argv[1])
print(config[sys.argv[2]][sys.argv[3]])

使用

python iniparser.py <filepath> <section> <key>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接