如何为Input设置超时

时间:2017-05-18 01:12:24

标签: python python-3.x

如果你等了4秒就会说'#34;你没时间了#34;这很好。但是,为了保持循环,您必须按enter键才能继续。

我想这样,当它打印时#34;你没时间"在下面而不仅仅是键入,它显示一个输入语句,如" Type' 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)

2 个答案:

答案 0 :(得分:1)

完成你提出的任务并不像你猜想的那么容易。使用signal模块更容易实现此目的:(我已将代码与修改版本的答案合并为linked

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

答案 1 :(得分:0)

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

$ pip install inputimeout

用法

from inputimeout import inputimeout, TimeoutOccurred
try:
    something = inputimeout(prompt='>>', timeout=5)
except TimeoutOccurred:
    something = 'something'
print(something)