【问题标题】:Triggering keyboardinterrupt only at a certain time仅在特定时间触发键盘中断
【发布时间】:2021-12-04 13:39:38
【问题描述】:

我正在尝试构建一个只能在特定时间触发 KeyboardInterrupt 异常的代码。 作为一个简单的例子,我构建了以下代码:

import time
from time import strftime

try:

    while True:
        time.sleep(1)

except time.time()%60>30 and KeyboardInterrupt:

    print("exited")

但是,当我运行它时,我收到以下错误:

TypeError: catching classes that do not inherit from BaseException is not allowed

我缺少一个简单的解决方案吗?

【问题讨论】:

  • 你能解释一下这段代码应该做什么吗?为什么你认为time.time()%60>30 属于except
  • 基本上我只是在超过 30 秒时才尝试退出代码。原因是我正在构建的代码会在每分钟 30 秒前执行几件事,并在代码运行时退出它会导致跟踪变量等问题。
  • 为什么你认为time.time()%60>30 属于except

标签: python-3.x


【解决方案1】:

先捕获异常,然后检查你的时间条件是否满足。

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        if time.time()%60>30:
            print("exited")  # here
            break
print("exited")  # or here as you like

【讨论】:

  • 谢谢!这非常有用:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多