繁体   English   中英

如何设置输入超时

[英]How to set a timeout for Input

如果你等了 4 秒,它会说“你没时间了”,这很好。 但是,为了继续循环,您必须按enter键才能继续。

我想要这样当它在下面打印“你用完了时间”而不仅仅是键入时,它会显示一个输入语句,如“键入'attack'以继续前进”并且循环将从它所在的位置继续。

from threading import Timer
import time

monsterhp = int(800)
y = 150
while monsterhp > 0:
    timeout = 4
    t = Timer(timeout, print, ['You ran out of time.'])
    t.start()
    print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = input(prompt)
    t.cancel()

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)

完成你提议的任务并不像你想象的那么容易。 使用signal模块更容易做到这一点:(我已将您的代码与我链接的答案的修改版本合并)

import signal, time

def TimedInput(prompt='', timeout=20, timeoutmsg = None):
    def timeout_error(*_):
        raise TimeoutError
    signal.signal(signal.SIGALRM, timeout_error)
    signal.alarm(timeout)
    try:
        answer = input(prompt)
        signal.alarm(0)
        return answer
    except TimeoutError:   
        if timeoutmsg:
            print(timeoutmsg)
        signal.signal(signal.SIGALRM, signal.SIG_IGN)
        return None

monsterhp = int(800)
y = 150
while monsterhp > 0:
    timeout = 4
    timeoutmsg = 'You ran out of time.'
    print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = TimedInput(prompt, timeout, timeoutmsg)

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)

注意:这只适用于所有 unix/mac 系统

您可以将 while 循环更改为此,以获得代码的改进版本:)

while monsterhp > 0:
        timeout = 4
        timeoutmsg = 'You ran out of time.'
        print(" ")
        prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
        answer = TimedInput(prompt, timeout, timeoutmsg)

        if answer == "attack":
            print("You strike the monster")
            time.sleep(1)
            monsterhp = monsterhp - y
            print("War Lord Health:", monsterhp)
        elif answer == None:
            print("The War Lord has killed you, you're now dead")
            print("Thanks for playing, \nGAME OVER")
            break

有一个新的库inputimeout用于带超时的标准输入

$ pip install inputimeout

用法

from inputimeout import inputimeout, TimeoutOccurred
try:
    string = inputimeout(prompt='>>', timeout=5)
except TimeoutOccurred:
    string = 'time is over'
print(string)
import datetime

def custom_time_input(msg, seconds):
    try:
        print(msg)
        # current time in seconds
        current_time = datetime.datetime.now()
        time_after = current_time + datetime.timedelta(seconds=seconds)
        while datetime.datetime.now() < time_after:
            print("Time left: ", end="")
            print(time_after - datetime.datetime.now(), end="\r")
            time.sleep(1)
        print("\n")
        return True
    except KeyboardInterrupt:
        return False

res = custom_time_input("If you want to create a new config file PRESS CTRL+C within 20 seconds!", 20)
if res:
    pass # nothing changed
else:
    pass # do something because user pressed ctrl+c

> Blockquote

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM