gpt4 book ai didi

python - 使用一次后禁用 KeyboardInterrupt

转载 作者:行者123 更新时间:2023-11-28 18:27:39 26 4
gpt4 key购买 nike

Cont = 1
while Cont == 1:
try:
while Cont == 1:
counter = counter + 0.1
counter = round(counter, 1)
print(counter)
time.sleep(0.1)
if counter == crashNumber:
Cont = 0
except KeyboardInterrupt:
Multiplier = counter

这里计数器会继续计数直到达到crashNumber,当按下Ctrl + C时,它会取这个数counter 的值,并将其用于 Multiplier 以供稍后使用。

但是我只想让用户有机会按一次,然后它就被禁用了。有什么办法可以做到这一点?

最佳答案

无论您是否愿意,KeyboardInterrupt 异常都会被抛出:因此,解决方案是在您的except block 中以不同的方式处理异常。我选择的实现将使用一个简单的 bool 值,该值以 True 开头,并在第一次中断时设置为 False:

import time

allow_interrupt = True
while True:
try:
time.sleep(1)
print ('...')
except KeyboardInterrupt:
if allow_interrupt:
print ('interrupted!')
allow_interrupt = False

如果这能解决您的用例,请告诉我。

关于python - 使用一次后禁用 KeyboardInterrupt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com