2011-05-21 56 views
1

我創建了一個功能timeout_func運行的另一個功能正常,並返回其輸出,但如果函數超過「秒」,它會返回一個字符串「失敗」。 基本上,這是一個解決方法,可以超時運行無限的函數。 (在Windows上Python 2.7版)(爲什麼我需要一個解決辦法,爲什麼我不能只是讓功能非無限因爲有時候你不能做到這一點,」叫錯誤中已知的方法,即:fd = os.open('/dev/ttyS0', os.O_RDWR)這是爲什麼發送這麼多變量?

不管怎麼說,我timeout_func從幫助啓發我在這裏獲得: kill a function after a certain time in windows

我的代碼的問題是,由於某種原因,do_this功能是接收14個變量,而不是一個運行時,我得到的錯誤味精。通過雙擊該腳本或從python.exe。從IDLE你不會有異常錯誤.... exception error message

但是,如果我將其更改爲:

def do_this(bob, jim): 
return bob, jim 

它工作得很好......

這是怎麼回事?它不喜歡1變量函數...?

import multiprocessing 
import Queue 


def wrapper(queue, func, func_args_tuple): 
    result = func(*func_args_tuple) 
    queue.put(result) 
    queue.close() 

def timeout_func(secs, func, func_args_tuple): 
    queue = multiprocessing.Queue(1) # Maximum size is 1 
    proc = multiprocessing.Process(target=wrapper, args=(queue, func, func_args_tuple)) 
    proc.start() 

    # Wait for TIMEOUT seconds 
    try: 
     result = queue.get(True, secs) 
    except Queue.Empty: 
     # Deal with lack of data somehow 
     result = 'FAILED' 
     print func_args_tuple 
    finally: 
     proc.terminate() 

    return result 


def do_this(bob): 
    return bob 

if __name__ == "__main__": 
    print timeout_func(10, do_this, ('i was returned')) 
    x = raw_input('done') 

回答

5

('i was returned')不是元組。它的計算結果爲一個字符串,就像(3+2)計算爲整數..

調用do_this(*('i was returned'))通行證序列'i was returned'的每個字母作爲單獨的參數 - 相當於:

do_this('i', ' ', 'w', 'a', 's', ' ', 'r', 'e', 't', 'u', 'r', 'n', 'e', 'd') 

使用('i was returned',)代替強制它成爲一個元組(由於後面的逗號)。