如何在Python中使用eventlet抛出异常?

3

I have a simply code:

import eventlet

def execute():
    print("Start")
    timeout = Timeout(3)
    try:
        print("First")
        sleep(4)
        print("Second")
    except:
        raise TimeoutException("Error")
    finally:
        timeout.cancel()
    print("Third")

这段代码应该抛出TimeoutException,因为“try”块中的代码执行时间超过3秒。但是这个异常在循环中被吞噬了,输出中看不到它。

以下为输出内容:

Start
First

Process finished with exit code 0

我该如何将这个异常输出?
2个回答

4

将sleep(4)更改为

eventlet.sleep(4)

1
这段代码不会输出 Start...,因为没有人调用 execute(),而且sleep未定义。请展示真实的代码,我将编辑答案。
目前有几种猜测:
  • 可能你已经使用了 from time import sleep,那么它就是 Eventlet timeout not exiting 的重复,并且问题在于你没有给 Eventlet 运行并意识到存在超时的机会,解决方法:在每个地方使用 eventlet.sleep() 或者只使用一次 eventlet.monkey_patch()
  • 也可能你根本没有导入 sleep,那么它就是一个 NameError: sleep,并且所有来自 execute 的异常都被调用者隐藏了。
  • 也可能你正将这段代码与 stderr 重定向到文件或 /dev/null
让我们也修复其他问题。
try:
  # ...
  sleeep()  # with 3 'e', invalid name
  open('file', 'rb')
  raise Http404
except:
  # here you catch *all* exceptions
  # in Python 2.x even SystemExit, KeyboardInterrupt, GeneratorExit
  #  - things you normally don't want to catch
  # but in any Python version, also NameError, IOError, OSError,
  # your application errors, etc, all irrelevant to timeout
  raise TimeoutException("Error")

在Python 2.x中,你永远不会只写except:而是只写except Exception:
所以让我们只捕获正确的异常。
try:
  # ...
  execute_other() # also has Timeout, but shorter, it will fire first
except eventlet.Timeout:
  # Now there may be other timeout inside `try` block and
  # you will accidentally handle someone else's timeout.
  raise TimeoutException("Error")

所以让我们验证它是你的。
timeout = eventlet.Timeout(3)
try:
  # ...
except eventlet.Timeout as t:
  if t is timeout:
    raise TimeoutException("Error")
  # else, reraise and give owner of another timeout a chance to handle it
  raise

这里是一些缩短语法的代码:

with eventlet.Timeout(3, TimeoutException("Error")):
  print("First")
  eventlet.sleep(4)
  print("Second")
print("Third")

我希望您确实需要将一个超时异常替换为另一个。

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