首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何设置输入的超时

如何设置输入的超时
EN

Stack Overflow用户
提问于 2017-05-18 01:12:24
回答 2查看 6.9K关注 0票数 7

如果你等了4秒,上面写着“你没时间了”,这很好。但是,为了保持循环正常,您必须按下enter键才能继续。

我希望当它在下面打印“你用完了时间”时,它会显示一个输入语句,比如“输入‘攻击’继续前进”,循环就会从原来的位置继续。

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-18 03:35:49

完成你提议的任务并不像你想象的那么容易。使用signal模块可以更容易地做到这一点:(我已经将您的代码与一个修改过的答案ilinked版本结合在一起)

代码语言:javascript
复制
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循环更改为此,以获得代码的改进版本:)

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2020-11-22 15:15:28

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

代码语言:javascript
复制
$ pip install inputimeout

用法

代码语言:javascript
复制
from inputimeout import inputimeout, TimeoutOccurred
try:
    string = inputimeout(prompt='>>', timeout=5)
except TimeoutOccurred:
    string = 'time is over'
print(string)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44037060

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档