簡體   English   中英

Python 池 - 當我遇到超時異常時,如何保持 Python 進程運行?

[英]Python Pool - How do I keep Python Process running when I get a timeout exception?

我正在使用 Python 多處理庫。 每當其中一個進程拋出超時錯誤時,我的應用程序就會自行結束。 我想保持流程正常進行。

我有一個訂閱隊列並監聽傳入消息的 function:

def process_msg(i):
   #get new message from the queue
   #process it
   import time
   time.sleep(10)
   return True

我創建了一個創建 6 個進程並執行上面的 process_msg() function 的池。 當 function 超時時,我希望池再次調用 function 並等待新消息而不是退出:


if __name__ == "main":

 import multiprocessing
 from multiprocessing import Pool

 pool = Pool(processes=6)
 collection = range(6)
 try:
  val = pool.map_async(process_msg, collection)
  try:
       res = val.get(5)
  except TimeoutError:
       print('timeout here')
 pool.close()
 pool.terminate()
 pool.join()

代碼運行,當我超時時,應用程序自行終止。

我想要它做的是打印發生的超時並再次調用相同的 function 。

什么是正確的方法?

這是一個有效程序的框架。 您遇到的主要問題是使用pool.terminate ,它“立即停止工作進程而不完成未完成的工作”(請參閱文檔)。

from multiprocessing import Pool, TimeoutError
def process_msg(i):
   #get new message from the queue
   #process it
   import time
   print(f"Starting to sleep, proxess # {i}")
   time.sleep(10)
   return True

def main():
    print("in main")
    pool = Pool(processes=6)
    collection = range(6)
    print("About to spawn sub processes")
    val = pool.map_async(process_msg, collection)
    while True: 
        try:
            print("Waiting for results")
            res = val.get(3)
            print(f"Res is {res}")
            break
        except TimeoutError:
            print("Timeout here")

    print("Closing pool")
    pool.close()
    # pool.terminate() # do not terminate - it kill the child processes 
    print ("Joining pool")
    pool.join()
    print("exiting main")

if __name__ == "__main__":
    main()
    

該代碼的output為:

in main
About to spawn sub processes
Waiting for results
Starting to sleep, proxess # 0
Starting to sleep, proxess # 1
Starting to sleep, proxess # 2
Starting to sleep, proxess # 3
Starting to sleep, proxess # 4
Starting to sleep, proxess # 5
Timeout here
Waiting for results
Timeout here
Waiting for results
Timeout here
Waiting for results
Res is [True, True, True, True, True, True]
Closing pool
Joining pool
exiting main

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM