Created
May 11, 2020 06:13
-
-
Save kemingy/73645c1c9034a2a8a75f42f48b8248a2 to your computer and use it in GitHub Desktop.
timeout for Python (signal, futures)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
from concurrent import futures | |
import signal | |
class Model: | |
def __init__(self): | |
self.pid = os.getpid() | |
def run(self): | |
time.sleep(1) | |
print('>> run: ', os.getpid()) | |
return self.pid | |
def __repr__(self): | |
return f'<{self.pid}>' | |
m = Model() | |
print(m) | |
# signal | |
def handler(signum, frame): | |
raise TimeoutError('Timeout') | |
signal.signal(signal.SIGALRM, handler) | |
try: | |
signal.alarm(2) | |
m.run() | |
signal.alarm(0) | |
except TimeoutError as err: | |
print('signal', err) | |
# async | |
with futures.ProcessPoolExecutor(max_workers=1) as pool: | |
try: | |
f = pool.submit(m.run) | |
print(f.result(timeout=0.1)) | |
except futures.TimeoutError as err: | |
print('try to cancel:', f.cancel()) | |
print('async timeout:', err) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
signal.alarm
is not available in Windowsfutures
is not able to cancel when it's running (unless you add event check)