私は曜日サーバーの見積もりを作成しています。私は、そのテキストの下で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-への書き込みを迅速にあなたはそれはあなたが使用する必要があります辞書、だかのようにデータを読み込むしようとしているようにそれはそう読んだ後
ブラケットは機能しません。 'get()'関数を使います。 'configOptions.host = conifg.get( 'サーバー'、 'ホスト')' http://docs.python.org/2/library/configparser.html#examples – M456
'config'を辞書のように扱いますが、それは' ConfigParser'インスタンスです... – kindall
今後、['ConfigParser'のドキュメントを参照してください(http://docs.python.org /2/library/configparser.html#configparser-objects)。 –