Home > Blockchain >  Threading in python - user input with timer
Threading in python - user input with timer

Time:04-12

I am trying to run two functions in parallel:

  1. Timer
  2. Input field

Program should terminate either when Timer ends or when user provides an answer. Everything is working fine, but when the time is up I still can input an answer, and I want process to terminate.

Can somebody help me with that issue ?

Thanks !

Here is my code:

import sys
import time
import threading

def countdown2(seconds):
    global stop_timer
    stop_timer = False
    start = time.time()
    while not stop_timer:
        if time.time() - start >= seconds:
            stop_timer = True
            print(f'End of time {time.time() - start}')

    print(f'End of time in {time.time() - start}')


countdown_thread = threading.Thread(target=countdown2, args=(5,))
countdown_thread.start()

while not stop_timer:

    answer = input('Provide answer: ')
    if answer:
        stop_timer = True
        break

print('End')

CodePudding user response:

Here's an example of how you could do this:

from threading import Thread
import time
import signal
import os

got_input = False

def countdown(duration):
    global got_input
    for _ in range(duration):
        time.sleep(1)
        if got_input:
            return
    if not got_input:
        os.kill(os.getpid(), signal.SIGINT)

def main():
    global got_input
    (t := Thread(target=countdown, args=[5])).start()
    try:
        answer = input('Please enter a value: ')
        got_input = True
        print(f'You entered: {answer}')
    except KeyboardInterrupt:
        print('\nToo slow')
    finally:
        t.join()

if __name__ == '__main__':
    main()
  • Related