input() suspends code execution waiting for user input. Is there any way to skip this line if, within X seconds, input() never received input?
- Related question: Keyboard input with timeout in Python - jfs
- solution for Python 3 - jfs
|
2 answers
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 - This is a bad decision: it leaves
input()calls weighing, that subsequent input can spoil (apart from other shortcomings in the implementation). Look at the solutions in the question I referred above - jfs
|
import multiprocessing.pool def input_timeout(text: str, timeout: int): return multiprocessing.pool.ThreadPool().apply_async(input, [text]).get(timeout) - this solution has the same problem as using Thread directly - jfs
|