input() suspends code execution waiting for user input. Is there any way to skip this line if, within X seconds, input() never received input?

2 answers 2

 import threading, time def timeout_input(prompt: str, timeout: int): result = [] threading.Thread(target=lambda: result.append(input(prompt)), daemon=True).start() t = time.time() while time.time()-t < timeout: time.sleep(.1) if len(result): return result[0] # input result print('TimeoutError %s' % timeout) a = timeout_input('enter a:', timeout=2) b = timeout_input('enter b:', timeout=1) print('a=%sb=%s' % (a, b)) 

out:

 enter a:123 enter b:TimeoutError 1 a=123 b=None 
 import multiprocessing.pool def input_timeout(text: str, timeout: int): return multiprocessing.pool.ThreadPool().apply_async(input, [text]).get(timeout)