【问题标题】:Timed user input in Python [duplicate]Python中的定时用户输入[重复]
【发布时间】:2021-11-24 06:05:33
【问题描述】:

我正在尝试使用计时器在 Python 中获取用户输入。我希望用户只有 10 秒的时间来输入内容。但是,当 10 秒结束时,消息“时间到了!”已打印,但脚本不会停止。

import pygame
from threading import Thread

clock = pygame.time.Clock()
timee = 0
UIn=None

def func1():
    global timee
    global clock
    global UIn
    while True:
        milli = clock.tick()
        seconds = milli/1000

        timee=timee+seconds
        if(int(timee)==10):
            print("Time is over")
            quit()
        

def func2():
    global UIn
    print("Working")
    input("Press key:\t")


Thread(target=func1).start()
Thread(target=func2).start()
UIn=input("Press key:\t")

【问题讨论】:

  • 我在this链接中回答了类似的问题

标签: python user-input pygame-clock


【解决方案1】:

您可以为此目的使用Timer

from threading import Timer

timeout = 10
t = Timer(timeout, print, ['Sorry, times up!'])
t.start()
prompt = "You have %d seconds to answer the question. What color do cherries have?...\n" % timeout
answer = input(prompt)
t.cancel()

输出:

You have 10 seconds to answer the question. What color do cherries have?
(After 10 seconds)
Sorry, times up!

【讨论】:

  • 当然要使用 if ... else 语句来获得正确答案。所以 ... if answer == "red": ... print("Correct") ... else: .... print("Try again")
  • Timer 是一个类,而不是一个库。另一方面,线程是包含它的库。
  • @COOL_IRON 感谢您的更正。我想更改和编辑此内容,但网站不允许。
  • 复制粘贴this thread .. ^^
  • 答案不正确,因为定时器没有取消inputInput 在时间是爱之后继续。问题是如何在 10 秒后“停止”input
【解决方案2】:

经过一番思考并感谢@Rabbid76,您可能想要这样的东西(根据this great post的代码修改):

import msvcrt
import time
import sys

class TimeoutExpired(Exception):
    pass

def input_with_timeout(prompt, timeout, timer=time.monotonic):
    """Timed input function, taken from https://stackoverflow.com/a/15533404/12892026"""
    sys.stdout.write(prompt)
    sys.stdout.flush()
    endtime = timer() + timeout
    result = []
    while timer() < endtime:
        if msvcrt.kbhit():
            result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
            if result[-1] == '\r':
                return ''.join(result[:-1])
        time.sleep(0.04) # just to yield to other processes/threads
    raise TimeoutExpired

# create a timed input object
try:
    answer = input_with_timeout("Give me an answer: ", 10)
except TimeoutExpired:
    print('\nSorry, times up')
else:
    print(f'\nYour answer was: {answer}')

# continue with code and verify the input
if answer:
    if answer == "yes":
        print("OK")

【讨论】:

  • msvcrt 是一个仅限 Windows 的模块,因此基于它的任何内容都是特定于平台的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 2018-05-06
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 2016-06-29
相关资源
最近更新 更多