Best Python code snippet using playwright-python
coordinator.py
Source:coordinator.py  
...37  ...start thread N...(coord, ...)38  # Wait for all the threads to terminate.39  coord.join(threads)40  ```41  Any of the threads can call `coord.request_stop()` to ask for all the threads42  to stop.  To cooperate with the requests, each thread must check for43  `coord.should_stop()` on a regular basis.  `coord.should_stop()` returns44  `True` as soon as `coord.request_stop()` has been called.45  A typical thread running with a coordinator will do something like:46  ```python47  while not coord.should_stop():48    ...do some work...49  ```50  #### Exception handling:51  A thread can report an exception to the coordinator as part of the52  `should_stop()` call.  The exception will be re-raised from the53  `coord.join()` call.54  Thread code:55  ```python56  try:57    while not coord.should_stop():58      ...do some work...59  except Exception as e:60    coord.request_stop(e)61  ```62  Main code:63  ```python64  try:65    ...66    coord = Coordinator()67    # Start a number of threads, passing the coordinator to each of them.68    ...start thread 1...(coord, ...)69    ...start thread N...(coord, ...)70    # Wait for all the threads to terminate.71    coord.join(threads)72  except Exception as e:73    ...exception that was passed to coord.request_stop()74  ```75  To simplify the thread implementation, the Coordinator provides a76  context handler `stop_on_exception()` that automatically requests a stop if77  an exception is raised.  Using the context handler the thread code above78  can be written as:79  ```python80  with coord.stop_on_exception():81    while not coord.should_stop():82      ...do some work...83  ```84  #### Grace period for stopping:85  After a thread has called `coord.request_stop()` the other threads have a86  fixed time to stop, this is called the 'stop grace period' and defaults to 287  minutes.  If any of the threads is still alive after the grace period expires88  `coord.join()` raises a RuntimeException reporting the laggards.89  ```python90  try:91    ...92    coord = Coordinator()93    # Start a number of threads, passing the coordinator to each of them.94    ...start thread 1...(coord, ...)95    ...start thread N...(coord, ...)96    # Wait for all the threads to terminate, give them 10s grace period97    coord.join(threads, stop_grace_period_secs=10)98  except RuntimeException:99    ...one of the threads took more than 10s to stop after request_stop()100    ...was called.101  except Exception:102    ...exception that was passed to coord.request_stop()103  ```104  """105  def __init__(self, clean_stop_exception_types=None):106    """Create a new Coordinator.107    Args:108      clean_stop_exception_types: Optional tuple of Exception types that should109        cause a clean stop of the coordinator. If an exception of one of these110        types is reported to `request_stop(ex)` the coordinator will behave as111        if `request_stop(None)` was called.  Defaults to112        `(tf.errors.OutOfRangeError,)` which is used by input queues to signal113        the end of input. When feeding training data from a Python iterator it114        is common to add `StopIteration` to this list.115    """116    if clean_stop_exception_types is None:117      clean_stop_exception_types = (errors.OutOfRangeError,)118    self._clean_stop_exception_types = tuple(clean_stop_exception_types)119    # Protects all attributes.120    self._lock = threading.Lock()121    # Event set when threads must stop.122    self._stop_event = threading.Event()123    # Python exc_info to report.124    # If not None, it should hold the returned value of sys.exc_info(), which is125    # a tuple containing exception (type, value, traceback).126    self._exc_info_to_raise = None127    # True if we have called join() already.128    self._joined = False129    # Set of threads registered for joining when join() is called.  These130    # threads will be joined in addition to the threads passed to the join()131    # call.  It's ok if threads are both registered and passed to the join()132    # call.133    self._registered_threads = set()134  def _filter_exception(self, ex):135    """Check if the exception indicated in 'ex' should be ignored.136    This method examines `ex` to check if it is an exception that should be137    reported to the users.  If yes, it returns `ex` as is, otherwise it returns138    None.139    The code returns None for exception types listed in140    `_clean_stop_exception_types`.141    Args:142      ex: None, an `Exception`, or a Python `exc_info` tuple as returned by143        `sys.exc_info()`.144    Returns:145      ex or None.146    """147    if isinstance(ex, tuple):148      ex2 = ex[1]149    else:150      ex2 = ex151    if isinstance(ex2, self._clean_stop_exception_types):152      # Ignore the exception.153      ex = None154    return ex155  def request_stop(self, ex=None):156    """Request that the threads stop.157    After this is called, calls to `should_stop()` will return `True`.158    Note: If an exception is being passed in, in must be in the context of159    handling the exception (i.e. `try: ... except Exception as ex: ...`) and not160    a newly created one.161    Args:162      ex: Optional `Exception`, or Python `exc_info` tuple as returned by163        `sys.exc_info()`.  If this is the first call to `request_stop()` the164        corresponding exception is recorded and re-raised from `join()`.165    """166    with self._lock:167      ex = self._filter_exception(ex)168      # If we have already joined the coordinator the exception will not have a169      # chance to be reported, so just raise it normally.  This can happen if170      # you continue to use a session have having stopped and joined the171      # coordinator threads.172      if self._joined:173        if isinstance(ex, tuple):174          six.reraise(*ex)175        elif ex is not None:176          # NOTE(touts): This is bogus if request_stop() is not called177          # from the exception handler that raised ex.178          six.reraise(*sys.exc_info())179      if not self._stop_event.is_set():180        if ex and self._exc_info_to_raise is None:181          if isinstance(ex, tuple):182            logging.info("Error reported to Coordinator: %s, %s",183                         type(ex[1]),184                         compat.as_str_any(ex[1]))185            self._exc_info_to_raise = ex186          else:187            logging.info("Error reported to Coordinator: %s, %s",188                         type(ex),189                         compat.as_str_any(ex))190            self._exc_info_to_raise = sys.exc_info()191          # self._exc_info_to_raise should contain a tuple containing exception192          # (type, value, traceback)193          if (len(self._exc_info_to_raise) != 3 or194              not self._exc_info_to_raise[0] or195              not self._exc_info_to_raise[1]):196            # Raise, catch and record the exception here so that error happens197            # where expected.198            try:199              raise ValueError(200                  "ex must be a tuple or sys.exc_info must return the current "201                  "exception: %s"202                  % self._exc_info_to_raise)203            except ValueError:204              # Record this error so it kills the coordinator properly.205              # NOTE(touts): As above, this is bogus if request_stop() is not206              # called from the exception handler that raised ex.207              self._exc_info_to_raise = sys.exc_info()208        self._stop_event.set()209  def clear_stop(self):210    """Clears the stop flag.211    After this is called, calls to `should_stop()` will return `False`.212    """213    with self._lock:214      self._joined = False215      self._exc_info_to_raise = None216      if self._stop_event.is_set():217        self._stop_event.clear()218  def should_stop(self):219    """Check if stop was requested.220    Returns:221      True if a stop was requested.222    """223    return self._stop_event.is_set()224  @contextlib.contextmanager225  def stop_on_exception(self):226    """Context manager to request stop when an Exception is raised.227    Code that uses a coordinator must catch exceptions and pass228    them to the `request_stop()` method to stop the other threads229    managed by the coordinator.230    This context handler simplifies the exception handling.231    Use it as follows:232    ```python233    with coord.stop_on_exception():234      # Any exception raised in the body of the with235      # clause is reported to the coordinator before terminating236      # the execution of the body.237      ...body...238    ```239    This is completely equivalent to the slightly longer code:240    ```python241    try:242      ...body...243    exception Exception as ex:244      coord.request_stop(ex)245    ```246    Yields:247      nothing.248    """249    # pylint: disable=broad-except250    try:251      yield252    except Exception as ex:253      self.request_stop(ex)254    # pylint: enable=broad-except255  def wait_for_stop(self, timeout=None):256    """Wait till the Coordinator is told to stop.257    Args:258      timeout: Float.  Sleep for up to that many seconds waiting for259        should_stop() to become True.260    Returns:261      True if the Coordinator is told stop, False if the timeout expired.262    """263    return self._stop_event.wait(timeout)264  def register_thread(self, thread):265    """Register a thread to join.266    Args:267      thread: A Python thread to join.268    """269    with self._lock:270      self._registered_threads.add(thread)271  def join(self, threads=None, stop_grace_period_secs=120,272           ignore_live_threads=False):273    """Wait for threads to terminate.274    This call blocks until a set of threads have terminated.  The set of thread275    is the union of the threads passed in the `threads` argument and the list276    of threads that registered with the coordinator by calling277    `Coordinator.register_thread()`.278    After the threads stop, if an `exc_info` was passed to `request_stop`, that279    exception is re-raised.280    Grace period handling: When `request_stop()` is called, threads are given281    'stop_grace_period_secs' seconds to terminate.  If any of them is still282    alive after that period expires, a `RuntimeError` is raised.  Note that if283    an `exc_info` was passed to `request_stop()` then it is raised instead of284    that `RuntimeError`.285    Args:286      threads: List of `threading.Threads`. The started threads to join in287        addition to the registered threads.288      stop_grace_period_secs: Number of seconds given to threads to stop after289        `request_stop()` has been called.290      ignore_live_threads: If `False`, raises an error if any of the threads are291        still alive after `stop_grace_period_secs`.292    Raises:293      RuntimeError: If any thread is still alive after `request_stop()`294        is called and the grace period expires.295    """296    # Threads registered after this call will not be joined.297    with self._lock:298      if threads is None:299        threads = self._registered_threads300      else:301        threads = self._registered_threads.union(set(threads))302      # Copy the set into a list to avoid race conditions where a new thread303      # is added while we are waiting.304      threads = list(threads)305    # Wait for all threads to stop or for request_stop() to be called.306    while any(t.is_alive() for t in threads) and not self.wait_for_stop(1.0):307      pass308    # If any thread is still alive, wait for the grace period to expire.309    # By the time this check is executed, threads may still be shutting down,310    # so we add a sleep of increasing duration to give them a chance to shut311    # down without loosing too many cycles.312    # The sleep duration is limited to the remaining grace duration.313    stop_wait_secs = 0.001314    while any(t.is_alive() for t in threads) and stop_grace_period_secs >= 0.0:315      time.sleep(stop_wait_secs)316      stop_grace_period_secs -= stop_wait_secs317      stop_wait_secs = 2 * stop_wait_secs318      # Keep the waiting period within sane bounds.319      # The minimum value is to avoid decreasing stop_wait_secs to a value...TimerLoop.py
Source:TimerLoop.py  
1import datetime2import time3# A Very Simple even loop where the only events are timeouts.4def _empty_func(name, now):5    print('firing empty cb for ' + name + ' at time ' + str(now))6    return False7class TimerLoop(object):8    def __init__(self):9        self.handlers = {}10        self.default_period = 111        self.loop_count = 012        self.last_tick = datetime.datetime.now()13    def addHandler(self, func, period, sid = None):14        if not sid:15            sid = 'handler_' + str(len(self.handlers.keys())+1)16        if not func:17            func = empty_func18        if not period:19            period = self.default_period20        handler = {21            'sid': sid,22            'func': func,23            'period': datetime.timedelta(seconds=period),24            'last_success': datetime.datetime.fromtimestamp(0),25            'last_attempt': datetime.datetime.fromtimestamp(0),26        }27        self.handlers[sid] = handler28        return sid29    def removeHandler(self, sid):30        if not sid:31            return False32        if not sid in self.handlers:33            return False34        del self.handlers[sid]35        return True36    def tick(self):37        now = datetime.datetime.now()38        request_stop = False39        for sid in self.handlers:40            period = self.handlers[sid]['period']41            last   = self.handlers[sid]['last_success']42            if (now - last) > period:43                func = self.handlers[sid]['func']44                try:45                    frv = func(sid, now)46                    self.handlers[sid]['last_success'] = now47                    if frv and isinstance(frv,bool):48                        request_stop = request_stop or frv49                except Exception as e:50                    print('Exception calling callback for ' + sid)51                    print(e)52                self.handlers[sid]['last_attempt'] = now53        self.loop_count += 154        self.last_tick = now55        return request_stop56    def run(self, tick_len = 0.5):57        running = True58        while running:59            stop = self.tick()60            if stop:61                running = False...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
