搜尋
首頁後端開發Python教學如何在程式設計中實現限時用戶輸入?

How Can I Implement Time-Limited User Input in Programming?

有時間限制的輸入

在程式設計中,對使用者輸入施加時間限制是有益的。例如,您可能希望向使用者詢問問題並為他們提供有限的回應時間,例如:

print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...\n")

如果使用者超過時間限制,您可以顯示類似以下的訊息:

print('Sorry, times up.')

限時輸入解決方案

實現限時輸入,考慮以下選項:

  • 阻止主執行緒:
from threading import Timer

timeout = 10
t = Timer(timeout, print, ['Sorry, times up'])
t.start()
prompt = "You have %d seconds to choose the correct answer...\n" % timeout
answer = input(prompt)
t.cancel()
阻止主執行緒:
  • 阻止主執行緒:
import msvcrt
import time

class TimeoutExpired(Exception):
    pass

def input_with_timeout(prompt, timeout, timer=time.monotonic):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() 
    阻止主執行緒:
  • 如果可以接受在使用者提供輸入時阻止程式碼的執行,則可以使用Timer 物件:
import select
import sys

def input_with_timeout(prompt, timeout):
    sys.stdout.write(prompt)
    sys.stdout.flush()
    ready, _, _ = select.select([sys.stdin], [],[], timeout)
    if ready:
        return sys.stdin.readline().rstrip('\n')  # expect stdin to be line-buffered
    raise TimeoutExpired
import signal

def alarm_handler(signum, frame):
    raise TimeoutExpired

def input_with_timeout(prompt, timeout):
    # set signal handler
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(timeout)  # produce SIGALRM in `timeout` seconds

    try:
        return input(prompt)
    finally:
        signal.alarm(0)  # cancel alarm
非阻塞輸入(Windows)

:為避免阻塞主線程,可以在Windows 上使用以下方法(注意此方法未經測試):

非阻塞輸入(Unix):或者,在基於Unix 的系統上,您可以使用以下其中一種方法:透過實作這些方法,您可以有效地對使用者輸入應用時間限制,增強使用者體驗並控製程式流程。

以上是如何在程式設計中實現限時用戶輸入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解差異:用於循環和python中的循環了解差異:用於循環和python中的循環May 16, 2025 am 12:17 AM

theDifferenceBetweewneaforoopandawhileLoopInpythonisthataThataThataThataThataThataThataNumberoFiterationSiskNownInAdvance,而leleawhileLoopisusedWhenaconDitionNeedneedneedneedNeedStobeCheckedStobeCheckedStobeCheckedStobeCheckedStobeceDrepeTysepectients.peatsiveSectlyStheStobeCeptellyWithnumberofiterations.1)forloopsareAceareIdealForitoringercortersence

Python循環控制:對於vs -a -a比較Python循環控制:對於vs -a -a比較May 16, 2025 am 12:16 AM

在Python中,for循環適用於已知迭代次數的情況,而while循環適合未知迭代次數且需要更多控制的情況。 1)for循環適用於遍歷序列,如列表、字符串等,代碼簡潔且Pythonic。 2)while循環在需要根據條件控制循環或等待用戶輸入時更合適,但需注意避免無限循環。 3)性能上,for循環略快,但差異通常不大。選擇合適的循環類型可以提高代碼的效率和可讀性。

如何在Python中結合兩個列表:5種簡單的方法如何在Python中結合兩個列表:5種簡單的方法May 16, 2025 am 12:16 AM

在Python中,可以通過五種方法合併列表:1)使用 運算符,簡單直觀,適用於小列表;2)使用extend()方法,直接修改原列表,適用於需要頻繁更新的列表;3)使用列表解析式,簡潔且可對元素進行操作;4)使用itertools.chain()函數,內存高效,適合大數據集;5)使用*運算符和zip()函數,適用於需要配對元素的場景。每種方法都有其特定用途和優缺點,選擇時應考慮項目需求和性能。

循環時循環:python語法,用例和示例循環時循環:python語法,用例和示例May 16, 2025 am 12:14 AM

foroopsare whenthenemberofiterationsisknown,而whileLoopsareUseduntilacTitionismet.1)ForloopSareIdealForeSequencesLikeLists,UsingSyntaxLike'forfruitinFruitinFruitinFruitIts:print(fruit)'。 2)'

python串聯列表列表python串聯列表列表May 16, 2025 am 12:08 AM

toConcateNateAlistofListsInpython,useextend,listComprehensions,itertools.Chain,orrecursiveFunctions.1)ExtendMethodStraightForwardButverBose.2)listComprechencomprechensionsareconconconciseandemandeconeandefforlargerdatasets.3)

Python中的合併列表:選擇正確的方法Python中的合併列表:選擇正確的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入兩個列表?如何在Python 3中加入兩個列表?May 14, 2025 am 12:09 AM

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

Python串聯列表字符串Python串聯列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)