2014-02-06 30 views
1

我有一個程序,實現了由於不正確地執行parallisation偶爾掛起的錯誤庫。檢測掛在OS X的python shell

我沒有時間去解決核心問題,所以我正在尋找一種方法來確定何時掛起這個過程而不是做它的工作。

是否有任何OS X或Python特定的API來執行此操作?是否有可能使用另一個線程甚至主線程來反覆解析stdout,以便在最後幾行在特定的時間內沒有改變時,另一個線程被通知並且可以殺死行爲不當的線程? (然後重新啓動?

回答

1

基本上你正在尋找一個監視器的過程,它會運行一個命令(或命令集),並觀看他們的執行尋找具體的事情(在你的情況下,stdout沉默)。引用2所以下面的問題(和一些文檔簡單的介紹一下),您可以快速構建一個超級簡單的監控。

https://stackoverflow.com/questions/2804543/read-subprocess-stdout-line-by-line https://stackoverflow.com/questions/3471461/raw-input-and-timeout

# monitor.py 
import subprocess 

TIMEOUT = 10 
while True: 
    # start a new process to monitor 
    # you could also run sys.argv[1:] for a more generic monitor 
    child = subprocess.Popen(['python','other.py','arg'], stdout=subprocess.PIPE) 
    while True: 
    rlist,_,_ = select([child.stdout], [], [], TIMEOUT) 
    if rlist: 
     child.stdout.read() # do you need to save the output? 
    else: 
     # timeout occurred, did the process finish? 
     if child.poll() is not None: 
     # child process completed (or was killed, but didn't hang), we are done 
     sys.exit() 
     else: 
     # otherwise, kill the child and start a new one 
     child.kill() 
     break