简体   繁体   中英

try/except does not raise error

In the following code,

import platform
import signal
import threading
import time

class TimeoutListener(object):
  def __init__(self, timeout_seconds, error_message="Timeout executing."):
    self.timeout_seconds = timeout_seconds
    self.error_message = error_message
    self.alarm = None

  def __enter__(self):
      signal.signal(signal.SIGALRM, self._handle_timeout)
      signal.alarm(int(self.timeout_seconds))

  def __exit__(self, listener_type, value, traceback):
    # Disable the alarm.
    if self.alarm:
      self.alarm = None
    else:
      signal.alarm(0)

  def _handle_timeout(self, signum, frame):
    print ("Got the signum %s with frame: %s" % (signum, frame))
    raise ValueError(self.error_message)


class TimedExecutor(object):
  @staticmethod
  def execute(timeout_secs, functor, *args, **kwargs):
    msg = "Timeout executing method - %s." % functor.__name__
    timeout_signal = TimeoutListener(timeout_secs, error_message=msg)

    try:
      with timeout_signal:
        output = functor(*args, **kwargs)
    except Exception as ex:
      print("%s did not complete in %s: %s."
            % (functor.__name__, timeout_secs, repr(ex)))
      raise
    return output

def foo():
  for _ in range(10):
    try:
      time.sleep(1)
      print("SLEEPING")
    except Exception as ex:
      print ex

ob = TimedExecutor.execute(1, foo)

I have TimedExecutor class, which raises error when a function does not complete execution within the given timeout period. The code works fine (ie raises error at timeout) when foo is defined as follow:

def foo():
  try:
    for _ in range(10):
      time.sleep(1)
      print("SLEEPING")
  except Exception as ex:
    print ex

whereas, if the same code of foo is written inside try/except, it does not raise any error (continues with execution). How could I make it raise the error, without making any changes to foo?

更改print exraise foo函数实现的范围。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM