2013-02-26 83 views
2

編輯 -我已經設法找到了解決方案,在頁面底部回答了我的問題。使用Python中的循環在.ini文件中設置配置解析器的已知數量的變量值

我有含有未知量的變量,由python腳本通過IRC界面創建一個.ini文件。

.ini文件的格式如下:

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

什麼,我想在.ini文件的varables要做的就是在.ini文件中每個個體varable追加到一個列表。

這是我使用試着和實現這一目標的主要的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) 

我發現varables的數量在.ini文件中使用此行:

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

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文件中追加每個vararable到列表

但這requries我知道varables的.ini文件,我不知道多少,這將是愚蠢的嘗試,像這樣的,因爲它規定了數量有限制的varables .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 [ '業主'] [Y])線帶來了以下錯誤:

KeyError: '0' 

documentaion對Python的configParser libary東張西望後,如果我是正確的,這個錯誤是由第2'的說法[Y]監守一個varable不能用來作爲參數引起的,即使varable包含一個字符串,可能是「1」,但bot_owners.append(setup_file ['owners'] [「1」])工作。

我要問這裏是什麼,是如果有另一種方式做到這一點,或者我怎麼能使用循環到每一個人varable追加一個.ini文件內到列表中。

希望我已經提供了足夠的信息供您嘗試和幫助。 感謝您的時間和幫助。

回答

3

不幸的是,ConfigParser本身並不真正支持列表。

如果有一個字符可以安全地用作分隔符,則一個OK解決方法是將列表打包成一個分隔字符串,然後在讀取配置文件時解壓字符串。

對於逗號分隔符:

[MYSECTION] 
mylist = item1,item2,item3 

然後在客戶端代碼中使用config.get('MYSECTION', 'mylist').split(',')

多行選項也是允許的。然後,它會像

[MYSECTION] 
mylist = 
    item1 
    item2 

而且你會在客戶端代碼中使用str.splitlines()

+0

啊,謝謝你,雖然在從未發生在我身上。使用'bot_owners =(setup_file ['owners'] ['1'])。split('|')'(使用'|'作爲分隔符)很有用,非常感謝! – Midareru 2013-02-26 05:15:24

0

在Python中實際使用一段時間後,讀完ConfigParser中的所有文檔。我設法找到了如何做到這一點,沒有線分隔符建議。

如果我有一個.ini文件是這樣的:使用此

[things] 
1 = not relavant at all 
[more_things] 
42 = don't need this 
[owners] 
1 = test 
2 = tesing123 

我可以追加所有存儲varables [owners]下。

import ConfigParser 

config = ConfigParser.ConfigParser() 
#File with the owner varables stored. 
config.read('test.ini') 
bot_owners = [] 

#Make sure the data is under the correct header. 
if config.has_section('owners') == True: 
    #find all the options under the [owners] header. 
    data_points = config.options('owners') 

    #Append the value assigned to the options to bot_owners 
    for var in data_points: 
     bot_owners.append(config.get('owners', var)) 

print bot_owners 

因此返回bot_owners['test', 'tesing123']