python input设置超时_python – 如何为Input设置超时

该博客介绍了如何在Python中为`input()`函数设置超时,以便在等待用户输入时可以控制时间限制。通过使用`threading.Timer`和`signal`模块两种方法实现,当超时时打印提示信息并处理后续逻辑。示例代码展示了一个模拟战斗场景,玩家需要在限定时间内输入'attack'来攻击怪物。
摘要由CSDN通过智能技术生成

如果你等了4秒就会说“你没时间了”这很好.但是,为了保持循环,你必须按回车键继续.

我想这样当它打印下面的“你没时间”而不是只是输入时,它会显示一个输入语句,如“类型’攻击’继续”,循环将从它的位置继续.

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)

最佳答案 完成你提出的任务并不像你猜想的那么容易.使用信号模块更容易:(我已将代码与修改后的版本I

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值