首頁 > 後端開發 > Python教學 > 如何在Python中實現使用者輸入逾時?

如何在Python中實現使用者輸入逾時?

Mary-Kate Olsen
發布: 2024-11-15 13:30:02
原創
431 人瀏覽過

How Can I Implement a Timeout for User Input in Python?

Timeout for User Input in Python

In Python, the raw_input() function prompts the user for input, but it waits indefinitely until the user enters something. For situations where you need to impose a time limit on user input, a solution is available using the threading module.

The raw_input_with_timeout() function, as proposed by a user, takes two arguments: prompt (the text displayed to the user) and timeout (the time limit in seconds). It starts a timer thread that will interrupt the main thread after the specified timeout.

Here's an improved version of the code:

import threading

def raw_input_with_timeout(prompt, timeout=30.0):
    print(prompt, end=' ')    
    timer = threading.Timer(timeout, thread.interrupt_main)
    astring = None
    try:
        timer.start()
        astring = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return astring
登入後複製

If the user enters input before the timeout, the input is returned as a string. If the timeout is reached, None is returned to indicate that the user did not provide input within the specified time frame.

Note that this solution assumes that the user is not typing very slowly. If you need to account for slow typing, you could recompute finishat (the time at which the timeout occurs) after every character input.

以上是如何在Python中實現使用者輸入逾時?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板