How to use the trio.Cancelled function in trio

To help you get started, we’ve selected a few trio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github goodboy / tractor / tests / test_cancellation.py View on Github external
assert len(err.exceptions) == subactor_breadth
            for subexc in err.exceptions:

                # verify first level actor errors are wrapped as remote
                if platform.system() == 'Windows':

                    # windows is often too slow and cancellation seems
                    # to happen before an actor is spawned
                    if isinstance(subexc, trio.Cancelled):
                        continue
                    else:
                        # on windows it seems we can't exactly be sure wtf
                        # will happen..
                        assert subexc.type in (
                            tractor.RemoteActorError,
                            trio.Cancelled,
                            trio.MultiError
                        )
                else:
                    assert isinstance(subexc, tractor.RemoteActorError)

                if depth > 0 and subactor_breadth > 1:
                    # XXX not sure what's up with this..
                    # on windows sometimes spawning is just too slow and
                    # we get back the (sent) cancel signal instead
                    if platform.system() == 'Windows':
                        assert (subexc.type is trio.MultiError) or (
                            subexc.type is tractor.RemoteActorError)
                    else:
                        assert subexc.type is trio.MultiError
                else:
                    assert (subexc.type is tractor.RemoteActorError) or (
github groove-x / trio-util / tests / test_exceptions.py View on Github external
    (multi_error_defer_to(trio.Cancelled, ValueError),
     trio.MultiError([_cancelled(), ValueError()]),
     trio.Cancelled),
    # nested MultiError
    (multi_error_defer_to(trio.Cancelled, ValueError),
     trio.MultiError([
         ValueError(),
         trio.MultiError([_cancelled(), _cancelled()])
     ]),
     trio.Cancelled),
    # exception subclass
    (multi_error_defer_to(MyExceptionBase, trio.Cancelled),
     trio.MultiError([_cancelled(), MyException()]),
     MyException),
    # exception objects with same repr are grouped
    (multi_error_defer_to(ValueError, trio.Cancelled),
     trio.MultiError([ValueError(), ValueError(), _cancelled()]),
github groove-x / trio-util / src / trio_util / _exceptions.py View on Github external
:param args:  One or more exception types which will defer to
        trio.Cancelled.  By default, all exception types will be filtered.

    Example::

        # If MultiError([Cancelled, Obstacle]) occurs, propagate only Cancelled
        # to the parent cancel scope.
        with defer_to_cancelled(Obstacle):
            try:
                # async call which may raise exception as part of API
                await advance(speed)
            except Obstacle:
                # handle API exception (unless Cancelled raised simultaneously)
                ...
    """
    return multi_error_defer_to(trio.Cancelled, *args)
github kivy / kivy / examples / async / trio_basic.py View on Github external
async def waste_time_freely():
    '''This method is also run by trio and periodically prints something.'''
    try:
        while True:
            print('Sitting on the beach')
            await trio.sleep(2)
    except trio.Cancelled as e:
        print('Wasting time was canceled', e)
    finally:
        # when canceled, print that it finished
        print('Done wasting time')
github goodboy / tractor / tractor / _trionics.py View on Github external
log.debug(
                        f"Waiting on subactors {anursery._children}"
                        "to complete"
                    )
                except (BaseException, Exception) as err:
                    # if the caller's scope errored then we activate our
                    # one-cancels-all supervisor strategy (don't
                    # worry more are coming).
                    anursery._join_procs.set()
                    try:
                        # XXX: hypothetically an error could be raised and then
                        # a cancel signal shows up slightly after in which case
                        # the `else:` block here might not complete?
                        # For now, shield both.
                        with trio.CancelScope(shield=True):
                            if err in (trio.Cancelled, KeyboardInterrupt):
                                log.warning(
                                    f"Nursery for {current_actor().uid} was "
                                    f"cancelled with {err}")
                            else:
                                log.exception(
                                    f"Nursery for {current_actor().uid} "
                                    f"errored with {err}, ")

                            # cancel all subactors
                            await anursery.cancel()

                    except trio.MultiError as merr:
                        # If we receive additional errors while waiting on
                        # remaining subactors that were cancelled,
                        # aggregate those errors with the original error
                        # that triggered this teardown.
github kivy / kivy / examples / async / trio_advanced.py View on Github external
try:
            i = 0
            while True:
                if self.root is not None:
                    status = self.root.ids.label.status
                    print('{} on the beach'.format(status))

                    # get some sleep
                    if self.root.ids.btn1.state != 'down' and i >= 2:
                        i = 0
                        print('Yawn, getting tired. Going to sleep')
                        self.root.ids.btn1.trigger_action()

                i += 1
                await trio.sleep(2)
        except trio.Cancelled as e:
            print('Wasting time was canceled', e)
        finally:
            # when canceled, print that it finished
            print('Done wasting time')
github RazerM / sqlalchemy_aio / sqlalchemy_aio / trio.py View on Github external
def thread_fn(self):
        while True:
            try:
                request = self._portal.run(self._receive_from_trio.receive)
            except (Cancelled, RunFinishedError):
                break
            except trio.EndOfChannel:
                with suppress(Cancelled, RunFinishedError):
                    self._portal.run(self._send_to_trio.aclose)
                break

            response = outcome.capture(request)
            self._portal.run(self._send_to_trio.send, response)
github HyperionGray / starbelly / starbelly / job.py View on Github external
def exc_filter(exc):
            ''' Filter out Cancelled exceptions raised by the nursery. '''
            if isinstance(exc, trio.Cancelled):
                return None
            return exc
github RazerM / sqlalchemy_aio / sqlalchemy_aio / trio.py View on Github external
def thread_fn(self):
        while True:
            try:
                request = self._portal.run(self._receive_from_trio.receive)
            except (Cancelled, RunFinishedError):
                break
            except trio.EndOfChannel:
                with suppress(Cancelled, RunFinishedError):
                    self._portal.run(self._send_to_trio.aclose)
                break

            response = outcome.capture(request)
            self._portal.run(self._send_to_trio.send, response)
github syncrypt / client / syncrypt / app / events.py View on Github external
def dispatch(self, event):
        '''
        This function will be call in the context of the watchdog worker
        thread. We need to use a BlockingTrioPortal to communicate with
        our trio program.
        '''
        with self.lock:
            try:
                trio.from_thread.run(self.handle_event, event, trio_token=self.token)
            except (trio.RunFinishedError, trio.Cancelled):
                pass
            except Exception:
                logger.exception('Unknown exception during trio.from_thread.run')