如何为输入设置超时时间

7
如果你等待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)

@abccd,我不太确定他的回复想让我理解什么。我对线程和线程还很陌生,你能告诉我需要在哪里放置吗?谢谢。还有,它必须要有一个函数吗?还是我们仍然可以使用我的大部分版本? - mykill456
你使用的是哪个操作系统? - Taku
Mac OS 最新的 Python。 - mykill456
3个回答

3

执行您提出的任务并不像您想象的那么容易。使用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

哇,我完全没有想到那个。顺便说一下,我简化了我的代码版本,以便更容易理解。https://pastebin.com/mbYgyucJ。这与你的第二个答案接近哈。但我将不得不在另一个小时内测试TimedInput,现在很忙。无论如何,感谢回复。 - mykill456
哇,谢谢,它起作用了。我简直不敢相信有这么多代码。再次感谢。 - mykill456

2

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

$ pip install inputimeout

用法

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

1
这个不行。它总是超时,而且在超时之前不检查输入的值。 - Abhishek Rai
@AbhishekRai,你做错了什么,它完美地工作了,尝试设置更长的超时时间,在输入后记得按回车键。分享你的代码。 - sound wave
1
让我再试一次。不行...失败了。这是在Windows上有效的方法。https://stackoverflow.com/questions/66262161/set-value-of-variable-if-nothing-is-entered-python-windowstimed-input/66265390#comment117154381_66265390 - Abhishek Rai
@AbhishekRai 我使用的是Windows 10,inputimeout很好用,看这张图片 https://i.imgur.com/6iEH9T6.png - sound wave
这个不起作用。 - undefined
@El_que_no_duda 你用的是什么操作系统?看看这个工作示例 https://i.imgur.com/BAxncmj.png - undefined

-2
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接