簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM