I've edited my post to use jcollado's idea which is simpler.
The multiprocessing.Process.join method has a timeout argument which you can use like this:
import multiprocessing as mp
import time
import logging
import re
logger = logging.getLogger(__name__)
def abc(string, result, wait = 0):
time.sleep(wait)
result.put(bool(re.match('some_pattern', string)))
if __name__ == '__main__':
logging.basicConfig(level = logging.DEBUG,
format = '%(asctime)s: %(message)s',
datefmt = '%H:%M:%S', )
result = mp.Queue()
proc = mp.Process(target = abc, args = ('some_pattern to match', result))
proc.start()
proc.join(timeout = 5)
if proc.is_alive():
proc.terminate()
else:
logger.info(result.get())
proc = mp.Process(target = abc, args = ('some string to match', result, 20))
proc.start()
proc.join(timeout = 5)
if proc.is_alive():
logger.info('Timed out')
proc.terminate()
else:
logger.info(result.get())
yields
12:07:59: True
12:08:04: Timed out
Note that you get the "Timed out" message in 5 seconds, even though abc('some string',20)
would have taken around 20 seconds to complete.