2013-12-13 42 views
1

我使用Python,即時通訊製作一個函數,讀取一個字符串,根據每行的第一個字執行不同的功能,我做了類似的東西,但它沒有做任何事情:閱讀一個文本並執行不同的功能,python

conf_list=''' 
host/yes/7200 
network/yes/6000 
applications/no/6500 
''' 

list_conf={} 
k=0 
for line in conf_list.splitlines(): 
    list_conf[k]=line 
    #print(list_conf[k]) 
    if list_conf[0] == 'host': 
     print(list_conf[1], list_conf[2]) #output i wanted: yes 7200 
    elif list_conf[0] == 'network': 
     print(list_conf[1], list_conf[2]) #output: yes 6000 
    elif list_conf[0] == 'applications': 
     print(list_conf[1], list_conf[2]) #output: no 6500 

也許這些if和elif不好?

+1

爲什麼是「應用程序」的輸出是「是6500」嗎?它在'conf_list'中是'no 6500'。 – roippi

+0

你是對的,我的錯誤,我現在改變它 –

回答

4

目前尚不清楚你實際上試圖做這裏。您正在創建一個字典,並以一個始終爲0的整數爲鍵,用每行重複替換該鍵的值,然後訪問該值並將其與您嘗試匹配的字符串進行比較。這沒有什麼用處。

認爲你想要的是這樣的:

list_confs = {} 
for line in conf_list.splitlines(): 
    thingy, yesno, number = line.split('/') 
    list_confs[thingy] = (thingy, yesno, number) 

現在你已經有了一個字典映射每個啄到的一組值。例如,'host'映射到'host', 'yes', '7200'這三個值。所以,你可以做這樣的事情:

list_conf = list_confs['host'] 
print(list_conf[1], list_conf[2]) # will print yes 7200 
2

如果yes是你的函數的名稱,你可以將其存儲在一個字典:

def yes: 
    ... 
def no: 
    ... 
functions = {'yes':yes, 'no':no} 

並執行它:

if list_conf[0] == 'host': 
    functions[list_conf[1]](list_conf[2]) 
1
conf_list='''host/yes/7200 
network/yes/6000 
applications/no/6500 
''' 

def call_host(*args): 
    print args 

def call_network(*args): 
    print args 

def call_applications(*args): 
    print args 

functions = { 
    'host': call_host, 
    'network': call_network, 
    'applications': call_applications, 
} 

for line in conf_list.splitlines(): 
    line = line.strip() 
    if not line: 
     continue 
    try: 
     # handle arbitrary whitespace 
     func_name, truth, value = [ i.strip() for i in line.split('/') ] 
     value = int(value) 
    except ValueError: 
     # get here for incorrect number of items or the failure to make the value an int 
     print "Malformed line:", line 
     continue 

    function = functions.get(func_name, None) 
    if function is None: 
     print "Unknown function:", line 
     continue 

    function(truth, value) 
1

在你的情況,你試圖執行一個功能之前,你最好檢查它是否是你的模塊中的功能:

import inspect 

conf_list=''' 
    host/yes/7200 
    network/yes/6000 
    applications/no/6500 
''' 
adict = {} 
for item in conf_list.splitlines(): 
    if item.strip(): 
     items = item.split('/') 
     tmp_list = [] 
     tmp_list.extend([items[1].strip(), items[2].strip()]) 
     adict[items[0].strip()] = tmp_list 
for func, args in adict.iteritems(): 
    isfunc = inspect.isfunction(locals().get(func, None)) 
    if isfunc: 
     locals().get(func)(args)