glenn-jocher commited on
Commit
d40481a
·
unverified ·
1 Parent(s): 8e3b4a0

Add `timeout()` class (#3460)

Browse files

* Add `timeout()` class

* rearrange order

Files changed (1) hide show
  1. utils/general.py +23 -1
utils/general.py CHANGED
@@ -1,5 +1,6 @@
1
  # YOLOv5 general utils
2
 
 
3
  import glob
4
  import logging
5
  import math
@@ -7,6 +8,7 @@ import os
7
  import platform
8
  import random
9
  import re
 
10
  import subprocess
11
  import time
12
  import urllib
@@ -34,6 +36,26 @@ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with Py
34
  os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def set_logging(rank=-1, verbose=True):
38
  logging.basicConfig(
39
  format="%(message)s",
@@ -86,7 +108,7 @@ def check_online():
86
  # Check internet connectivity
87
  import socket
88
  try:
89
- socket.create_connection(("1.1.1.1", 443), 5) # check host accesability
90
  return True
91
  except OSError:
92
  return False
 
1
  # YOLOv5 general utils
2
 
3
+ import contextlib
4
  import glob
5
  import logging
6
  import math
 
8
  import platform
9
  import random
10
  import re
11
+ import signal
12
  import subprocess
13
  import time
14
  import urllib
 
36
  os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
37
 
38
 
39
+ class timeout(contextlib.ContextDecorator):
40
+ # Usage: @timeout(seconds) decorator or 'with timeout(seconds):' context manager
41
+ def __init__(self, seconds, *, timeout_message="", suppress_timeout_errors=True):
42
+ self.seconds = int(seconds)
43
+ self.timeout_message = timeout_message
44
+ self.suppress = bool(suppress_timeout_errors)
45
+
46
+ def _timeout_handler(self, signum, frame):
47
+ raise TimeoutError(self.timeout_message)
48
+
49
+ def __enter__(self):
50
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
51
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
52
+
53
+ def __exit__(self, exc_type, exc_val, exc_tb):
54
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
55
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
56
+ return True
57
+
58
+
59
  def set_logging(rank=-1, verbose=True):
60
  logging.basicConfig(
61
  format="%(message)s",
 
108
  # Check internet connectivity
109
  import socket
110
  try:
111
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
112
  return True
113
  except OSError:
114
  return False