2017-05-22 19 views
1

我有一個線程應該執行最多3分鐘。如果超過3分鐘,我需要殺死它。我現在的代碼片段如下。請注意我不能在python中使用多處理模塊。在Python中運行一段時間的線程

def test_th(): 
     p = threading.Thread(target=update_fm,name="update_fm", args=(url,)) 
     p.start() 
     p.join(180) 
     log.debug("isalive :",p.isAlive()) 

def update_fm(fv_path): 
    output = None 
    try: 
     output = subprocess.check_output('wget {0} -O /tmp/test_fm'.format(fv_path), stderr=subprocess.STDOUT, shell=True) 
    except: 
     log.error("Error while downloading package, please try again") 
     return FAIL 
    if output: 
     log.info('going to upgrade cool :)') 
     return SUCCESS 
    return FAIL 
+0

那麼有什麼不工作? –

+0

@HoriaComan 3分鐘後不退出。我需要停止線程。 – Arun

回答

1

由於線程運行的命令,你不能阻止它容易(Is there any way to kill a Thread in Python?

,但你可以幫助線程通過中止進程正常退出正在執行的線程繼續(和出口) :

  • 通過Popen
  • 取代check_output得到Popen手柄,確保它的全球
  • 在3分鐘後,殺手柄:線程退出

讓我們從一個獨立的例子簡化它(窗口,通過在其他平臺上其他一些阻擋的東西代替notepad):

import threading,subprocess 

handle = None 

def update_fm(): 
    global handle 
    output = None 
    handle = subprocess.Popen('notepad',stdout=subprocess.PIPE) 
    output = handle.stdout.read() 
    rc = handle.wait() # at this point, if process is killed, the thread exits with 
    print(rc) 

def test_th(): 
     p = threading.Thread(target=update_fm) 
     p.start() 
     p.join(10) 
     if handle: 
      handle.terminate() 

test_th() 

在這裏,如果您在超時前關閉記事本窗口,則會返回代碼0,如果您等待10秒鐘,則會終止進程,您將返回代碼1.

您的錯誤處理的難度將從「過程中遇難」和「折磨錯誤「。當進程被殺死以改變它時,你可以設置另一個標誌。