2014-01-11 63 views
1

終止Python進程看看這個簡單的Python代碼流程:在有限的時間

from multiprocessing import Process 
import time 

def f(name): 
    time.sleep(100) 
    print 'hello', name 

if __name__ == '__main__': 
    p = Process(target=f, args=('bob',)) 
    p.start()#Has to be terminated in 5 seconds 
    #p.join() 
    print "This Needs to be Printed Immediately" 

我想我正在尋找像p.start(timeout)功能。

我想終止p過程,如果它沒有在5秒鐘內自行完成。我怎樣才能做到這一點?似乎沒有這樣的功能。

如果p.join()是註釋掉,下面print線將不得不等待百秒,不能「印刷Immediately'.But我希望它馬上這樣做的p.join()有被註釋掉。

+0

它可能不是最好的選擇,但如果你真的想要一個過程,你應該能夠終止它通過發送信號到過程(因爲您可以訪問其PID)。 –

回答

1

使用單獨的線程啓動進程,等待5秒鐘,然後終止進程。同時,主線程可以做你想要立即發生的工作:基本上只是使用時間模塊

def run_process_with_timeout(timeout, target, args): 
    p = Process(target=target, args=args) 
    running = False 
    second = int(time.strftime("%S")) 
    if second+timeout > 59: 
     second = (second+timeout)-60 
    else: 
     second = second+timeout 
    print second 
    while second > int(time.strftime("%S")): 
     if running == False: 
      p.start() 
      running = True 
    p.terminate() 

允許一個循環五秒鐘運行,則:

from multiprocessing import Process 
import time 
import threading 

def f(name): 
    time.sleep(100) 
    print 'hello', name 

def run_process_with_timeout(timeout, target, args): 
    p = Process(target=target, args=args) 
    p.start() 
    time.sleep(timeout) 
    p.terminate() 

if __name__ == '__main__': 
    t = threading.Thread(target=run_process_with_timeout, args=(5,f,('bob',))) 
    t.start() 
    print "This Needs to be Printed Immediately" 
+0

「在單獨的線程中運行進程」非常有趣的解決方案。 –

0

你說得對,在子進程庫中沒有Python 2.x中的這樣的函數。 但是,與Python 3.3,你可以使用:

p = subprocess.Popen(...) 
try: 
    p.wait(timeout=5) 
except TimeoutError: 
    p.kill() 

對於較早版本的Python,你會寫一個循環,調用p.poll()和檢查返回碼,例如每秒一次。

這是(就像普遍的投票一樣)從性能角度來看並不是最佳的,但它總是取決於你期望的。

1

你可能想看看that SO thread

基本上他們的解決方案是通過在單獨的線程中運行進程來使用線程模塊的超時功能。

0

嘗試是這樣的繼續前進,這假定超時時間以秒爲單位。 雖然我會指出,如果這是與OP最初發布的代碼一起使用的,這將起作用,因爲print是在與循環分開的第二個函數中,並且將在調用此函數後立即執行。

0

爲什麼不使用的Process.join()超時選項,如:

import sys 
... 
if __name__ == '__main__': 
    p = Process(target=f, args=('bob',)) 
    p.start()#Has to be terminated in 5 seconds 
    # print immediately and flush output 
    print "This Needs to be Printed Immediately" 
    sys.stdout.flush() 
    p.join(5) 
    if p.is_alive(): 
     p.terminate() 
+0

你解決了這個問題,如果'print'行實際上是'return'行呢?那麼你的代碼將無法工作。 –

+0

在你的問題中,你說你想要立即打印,所以這就是我所說的。如果你想退出程序並在5秒後自動終止程序,你將不得不啓動一個守護程序進程,如果有必要的話執行p.join(5)和p.terminate()。請參閱http://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.daemon – miraculixx