在 python 中线程化 - 带计时器的用户输入

Threading in python - user input with timer

我正在尝试 运行 并行执行两个函数:

  1. 计时器
  2. 输入字段

程序应在计时器结束或用户提供答案时终止。 一切正常,但时间到了我仍然可以输入答案,我希望进程终止。

有人可以帮我解决这个问题吗?

谢谢!

这是我的代码:

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')

这是一个如何执行此操作的示例:

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()