我有這行代碼(“model.predict(image=img)”),如果它需要超過 5 分鐘,我想停止執行。我可以使用python中的簡單方法或庫來實作這一點嗎?
for filename in os.listdir():
if filename.endswith(".jpg") or filename.endswith(".png"):
print(filename)
img = DataURI.from_file(filename)
#This should run for no longer than 5 minutes
output = model.predict(image=img)
#if this took more than 5 minutes to run, use "continue"
#continue
uj5u.com熱心網友回復:
我知道的解決方案是使用執行緒作業者并殺死它。一個作業人員運行該功能,我們還有另一個功能來維護運行時間。
我認為您可以使用python-worker(鏈接)
import time
from worker import worker
def run_with_timeout(worker_object, timeout):
while worker_object.work_time < timeout:
time.sleep(0.01) # give interval for checking
worker_object.abort()
@worker
def my_controlled_function(a, b, c):
...
## then you can run it
run_with_timeout(my_controlled_function(1, 2, 3), timeout=10)
uj5u.com熱心網友回復:
你可以使用這樣的東西:
for filename in os.listdir():
if filename.endswith(".jpg") or filename.endswith(".png"):
print(filename)
for x in range(0, 300) #Converting Minutes to seconds so 300
try:
img = DataURI.from_file(filename)
output = model.predict(image=img)
break
except:
time.sleep(1)
#if this took more than 5 minutes to run, use "continue"
#continue
這樣做就像它基本上會嘗試每 1 秒檢查一次,直到完全 5 分鐘。
或者如果這不起作用,您可以參考這篇文章,這可能有助于鏈接:函式呼叫超時
uj5u.com熱心網友回復:
您的model.predict()方法可能是 CPU 系結操作。在 Linux 中,您可以使用信號機制來中斷您當前的操作,但 Windows 作業系統沒有所有 POSIX 信號功能,因此我們可以使用thread或multiprocess立即進行interrupt/terminate一些操作。Python提供了一個使用 終止執行緒的好選擇ctypes.pythonapi.PyThreadState_SetAsyncExc,但這不會在I/O(如果執行緒阻塞)操作完成之前終止執行緒
這是一個簡單的例子:
import threading
import ctypes
import time
class TimeoutException(Exception):
pass
def f(arg):
while 1:
time.sleep(1)
print("hello")
class Timeout(threading.Thread):
def __init__(self,func,arg,timeout):
self.func = func
self.arg = arg
self.thread_ident = None
self.output = None
self.wait_for_finish = threading.Event()
threading.Thread.__init__(self)
self.killer = threading.Timer(timeout, self.raise_exception)
self.start()
self.wait_for_finish.wait()
def raise_exception(self):
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(self.thread_ident),
ctypes.py_object(TimeoutException))
def run(self):
self.thread_ident = threading.get_ident()
self.killer.start()
try:
self.output = self.func(self.arg)
except TimeoutException:
self.output = "Timeout exception"
finally:
self.wait_for_finish.set()
self.killer.cancel()
output = Timeout(func=f, arg=5, timeout = 5).output
print(output)
你也可以看看這個
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/529414.html
上一篇:PHP和子行程
