2

編集 - ページの下部に回答があり、問題の解決策を見つけることができました。

IRC インターフェイスを介して Python スクリプトによって作成された、不明な量の変数を含む .ini ファイルがあります。

.ini ファイルの形式は次のとおりです。

[varables]
0 = example
1 = example2
2 = exapmle3
#and so on.

.ini ファイルの変数でやりたいことは、.ini ファイルの個々の変数をリストに追加することです。

これは、これを実行するために使用しているメインの Python ファイルのコードです (ファイル全体ではなく、このタスクを実行するために使用されているものです)。

import ConfigParser
import os

#Config parser: 
class UnknownValue(Exception): pass
def replace_line(old_line, new_line):
    f = open("setup.ini")
    for line in f:
        line = os.linesep.join([s for s in line.splitlines() if s])
        if line == old_line:
            f1 = open("setup.ini",'r')
            stuff = f1.read()
            f1.close()
            new_stuff = re.sub(old_line,new_line,stuff)
            f = open("setup.ini",'w')
            f.write(new_stuff)
            f.close()        
def get_options(filename):
    config = ConfigParser.ConfigParser()
    try:
        config.read(filename)
    except ConfigParser.ParsingError, e:
        pass
    sections = config.sections()
    output = {}
    for section in sections:
        output[section] = {}
        for opt in config.options(section):
            value = config.get(section, opt)
            output[section][opt] = value
    return output

bot_owners = []#this becomes a list with every varable in the .ini file.


#gets the number of varables to be set, then loops appending each entry into their corosponding lists for later use.
setup_file = get_options("owner.ini")
num_lines = (sum(1 for line in open('owner.ini'))-1)#gets amount of varables in the file, and removes 1 for the header tag.
print "lines ", num_lines
x = 0
while x != num_lines:
    #loops through appending all the varables inside of the .ini file to the list 'bot_owners'
    y = str(x)
    bot_owners.append(setup_file['owners'][y])#this fails becuase it can't take a varable as a argument?
    x += 1

print (bot_owners)
print (num_lines)

次の行を使用して、.ini ファイル内の変数の数を確認します。

num_lines = (sum(1 for line in open('owner.ini'))-1)#gets amount of varables in the file, and removes 1 for the header tag.

これを行うことで、.ini ファイル内の各変数をリストに追加できます。

bot_owners.append(setup_file['owners']['0'])
bot_owners.append(setup_file['owners']['1'])
bot_owners.append(setup_file['owners']['2'])
#ect

しかし、これは私が知ることができない.iniファイル内の変数の数を知る必要があり、.iniファイルに含めることができる変数の量に制限を課すため、このようにしようとするのはばかげています.必要なコードははるかに少なくてすみます。

if num_lines == 1:    
    bot_owners.append(setup_file['owners']['0'])
elif num_lines == 2:
    bot_owners.append(setup_file['owners']['1'])
elif num_lines == 3:
    bot_owners.append(setup_file['owners']['2'])
#ect

ただし、このコードの問題点は、私のループにあります。

x = 0 #what varable is going to be appended
while x != num_lines:
    #loops through appending all the varables inside of the .ini file to the list 'bot_owners'
    y = str(x)
    bot_owners.append(setup_file['owners'][y]) #<-- THE PROBLEM
    x += 1

bot_owners.append (setup_file['owners'][y])行で次のエラーが表示されます。

KeyError: '0'

Python の configParser ライブラリのドキュメントを調べた後、私が正しければ、このエラーは 2 番目の引数[y]が原因で発生します。変数に文字列が含まれていても、変数を引数として使用できないためです。 「1」になる可能性がありますが、bot_owners.append(setup_file['owners']["1"])は機能します。

ここで私が求めているのは、これを行う別の方法があるかどうか、またはループを使用して .ini ファイル内の個々の変数をリストに追加する方法です。

4

2 に答える 2

3

残念ながら、ConfigParserリストをネイティブにサポートしていません。

区切り文字として安全に使用できる文字がある場合、問題のない回避策は、リストを区切られた文字列にパックし、構成ファイルを読み取るときに文字列をアンパックすることです。

コンマ区切りの場合:

[MYSECTION]
mylist = item1,item2,item3

次にconfig.get('MYSECTION', 'mylist').split(',')、クライアント コードで使用します。

複数行のオプションも使用できます。それは次のようなものになります

[MYSECTION]
mylist = 
    item1
    item2

そしてstr.splitlines()、クライアントコードで使用します。

于 2013-02-26T05:08:12.713 に答える