我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用asyncio.CancelledError()。
def vault_updater(self): await self.bot.wait_until_ready() try: await asyncio.sleep(20) # Start-up Time while True: servers = [x.id for x in self.bot.servers if x.id in self.system["Servers"]] for server in servers: for target in self.system["Servers"][server]["Targets"]: vault = self.system["Servers"][server]["Targets"][target]["Vault"] vault_max = self.system["Servers"][server]["Targets"][target]["Vault Max"] if vault < vault_max: increment = min(vault + int(vault_max * 0.04), vault_max) self.system["Servers"][server]["Targets"][target]["Vault"] = increment else: pass self.save_system() await asyncio.sleep(120) # task runs every 120 seconds except asyncio.CancelledError: pass
def ensure_future(coro, loop=None): """ Wrapper for asyncio.ensure_future which dumps exceptions """ if loop is None: loop = asyncio.get_event_loop() fut = asyncio.ensure_future(coro, loop=loop) def exception_logging_done_cb(fut): try: e = fut.exception() except asyncio.CancelledError: return if e is not None: loop.call_exception_handler({ 'message': 'Unhandled exception in async future', 'future': fut, 'exception': e, }) fut.add_done_callback(exception_logging_done_cb) return fut
def longpoll_run(self, custom_process=False): self.main_task = Task(self.longpoll_processor()) if custom_process: return self.main_task self.logger.info("Started to process messages") try: self.loop.run_until_complete(self.main_task) except (KeyboardInterrupt, SystemExit): self.stop() self.logger.info("Stopped to process messages") except asyncio.CancelledError: pass
def run(self): self.root.log.info("Starting task %s" % self) self._start_jobs() if not self.jobs: # TODO self._finished.set() return for cb in self.root.task_start_handlers: cb(self) while not self._finished.is_set(): try: await self._finished.wait() self.finished_at = time.time() except asyncio.CancelledError: self.root.log.info("Cancelled %s" % self) for fut in self._job_futures: fut.cancel() return
def reload(self): """Wait for reload events and reload config when event set.""" while 1: try: yield from self.reload_event.wait() self.log.info("Reloading configuration...") except asyncio.CancelledError: return finally: self.reload_event.clear() try: config = Config(self, self.filename, self.verbose) self.log.debug("New config instance %s" % config) yield from config.validate() self.config = config self.log.info("Done") except asyncio.CancelledError: return except Exception: self.log.exception("Error loading new config")
def test_cancel_make_subprocess_transport_exec(self): @asyncio.coroutine def cancel_make_transport(): coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, loop=self.loop) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: yield from task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport())
def test_cancel_post_init(self): @asyncio.coroutine def cancel_make_transport(): coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: yield from task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) test_utils.run_briefly(self.loop)
def test_wait_for_handle_cancel(self): event = _overlapped.CreateEvent(None, True, False, None) self.addCleanup(_winapi.CloseHandle, event) # Wait for unset event with a cancelled future; # CancelledError should be raised immediately fut = self.loop._proactor.wait_for_handle(event, 10) fut.cancel() start = self.loop.time() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(fut) elapsed = self.loop.time() - start self.assertTrue(0 <= elapsed < 0.1, elapsed) # Tulip issue #195: cancelling a _WaitHandleFuture twice must not crash fut = self.loop._proactor.wait_for_handle(event) fut.cancel() fut.cancel()
def test_cancel(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) yield 0 loop = self.new_test_loop(gen) @asyncio.coroutine def task(): yield from asyncio.sleep(10.0, loop=loop) return 12 t = asyncio.Task(task(), loop=loop) loop.call_soon(t.cancel) with self.assertRaises(asyncio.CancelledError): loop.run_until_complete(t) self.assertTrue(t.done()) self.assertTrue(t.cancelled()) self.assertFalse(t.cancel())
def test_cancel_both_task_and_inner_future(self): f = asyncio.Future(loop=self.loop) @asyncio.coroutine def task(): yield from f return 12 t = asyncio.Task(task(), loop=self.loop) test_utils.run_briefly(self.loop) f.cancel() t.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(t) self.assertTrue(t.done()) self.assertTrue(f.cancelled()) self.assertTrue(t.cancelled())
def test_cancel_task_catching(self): fut1 = asyncio.Future(loop=self.loop) fut2 = asyncio.Future(loop=self.loop) @asyncio.coroutine def task(): yield from fut1 try: yield from fut2 except asyncio.CancelledError: return 42 t = asyncio.Task(task(), loop=self.loop) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut1) # White-box test. fut1.set_result(None) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut2) # White-box test. t.cancel() self.assertTrue(fut2.cancelled()) res = self.loop.run_until_complete(t) self.assertEqual(res, 42) self.assertFalse(t.cancelled())
def test_cancel_current_task(self): loop = asyncio.new_event_loop() self.set_event_loop(loop) @asyncio.coroutine def task(): t.cancel() self.assertTrue(t._must_cancel) # White-box test. # The sleep should be cancelled immediately. yield from asyncio.sleep(100, loop=loop) return 12 t = asyncio.Task(task(), loop=loop) self.assertRaises( asyncio.CancelledError, loop.run_until_complete, t) self.assertTrue(t.done()) self.assertFalse(t._must_cancel) # White-box test. self.assertFalse(t.cancel())
def test_task_cancel_waiter_future(self): fut = asyncio.Future(loop=self.loop) @asyncio.coroutine def coro(): yield from fut task = asyncio.Task(coro(), loop=self.loop) test_utils.run_briefly(self.loop) self.assertIs(task._fut_waiter, fut) task.cancel() test_utils.run_briefly(self.loop) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, task) self.assertIsNone(task._fut_waiter) self.assertTrue(fut.cancelled())
def test_shield_effect(self): # Cancelling outer() does not affect inner(). proof = 0 waiter = asyncio.Future(loop=self.loop) @asyncio.coroutine def inner(): nonlocal proof yield from waiter proof += 1 @asyncio.coroutine def outer(): nonlocal proof yield from asyncio.shield(inner(), loop=self.loop) proof += 100 f = asyncio.async(outer(), loop=self.loop) test_utils.run_briefly(self.loop) f.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(f) waiter.set_result(None) test_utils.run_briefly(self.loop) self.assertEqual(proof, 1)
def test_gather_shield(self): child1 = asyncio.Future(loop=self.loop) child2 = asyncio.Future(loop=self.loop) inner1 = asyncio.shield(child1, loop=self.loop) inner2 = asyncio.shield(child2, loop=self.loop) parent = asyncio.gather(inner1, inner2, loop=self.loop) test_utils.run_briefly(self.loop) parent.cancel() # This should cancel inner1 and inner2 but bot child1 and child2. test_utils.run_briefly(self.loop) self.assertIsInstance(parent.exception(), asyncio.CancelledError) self.assertTrue(inner1.cancelled()) self.assertTrue(inner2.cancelled()) child1.set_result(1) child2.set_result(2) test_utils.run_briefly(self.loop)
def _test_cancel_wait_for(self, timeout): loop = asyncio.new_event_loop() self.addCleanup(loop.close) @asyncio.coroutine def blocking_coroutine(): fut = asyncio.Future(loop=loop) # Block: fut result is never set yield from fut task = loop.create_task(blocking_coroutine()) wait = loop.create_task(asyncio.wait_for(task, timeout, loop=loop)) loop.call_soon(wait.cancel) self.assertRaises(asyncio.CancelledError, loop.run_until_complete, wait) # Python issue #23219: cancelling the wait must also cancel the task self.assertTrue(task.cancelled())
def test_one_cancellation(self): a, b, c, d, e = [asyncio.Future(loop=self.one_loop) for i in range(5)] fut = asyncio.gather(a, b, c, d, e) cb = test_utils.MockCallback() fut.add_done_callback(cb) a.set_result(1) b.cancel() self._run_loop(self.one_loop) self.assertTrue(fut.done()) cb.assert_called_once_with(fut) self.assertFalse(fut.cancelled()) self.assertIsInstance(fut.exception(), asyncio.CancelledError) # Does nothing c.set_result(3) d.cancel() e.set_exception(RuntimeError()) e.exception()
def test_every_param_loop(self): asyncio.set_event_loop(None) # scheduled executions 1, 3, 5, 7, 9 schedule = self.schedule_manager.every(self.get_coroutine, timedelta(seconds=2), datetime.now() + timedelta(seconds=1), loop=self.loop) # will be cancelled at cancel_in_seconds = 10 async def cancel_schedule(): await asyncio.sleep(cancel_in_seconds, loop=self.loop) self.schedule_manager.cancel(schedule, running_jobs=True) try: self.loop.run_until_complete( asyncio.gather(cancel_schedule(), schedule.future, loop=self.loop)) except asyncio.CancelledError: pass # making sure that all running jobs and the schedule are cancelled self.loop.run_until_complete(asyncio.sleep(10, loop=self.loop)) self.assertEqual(5, self.count) asyncio.set_event_loop(self.loop)
def test_start_at_now(self): self.schedule = aschedule.every(self.sample_job, seconds=self.interval_in_seconds, start_at=datetime.datetime.now()) start_time = self.loop.time() # error if: the future doesn't exit or produces other than CancelledError with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(future=self.schedule.future) end_time = self.loop.time() # error if: given start_at, the job doesn't execute 5 times within 8 seconds. self.assertAlmostEqual(start_time + self.interval_in_seconds * (self.count_max - 1), end_time, places=0) # should behave the same as test_start_at
def test_start_at_after(self): after_in_seconds = 10 start_at = datetime.datetime.now() + datetime.timedelta(seconds=after_in_seconds) self.schedule = aschedule.every(self.sample_job, seconds=self.interval_in_seconds, start_at=start_at) start_time = self.loop.time() # error if: the future doesn't exit or produces other than CancelledError with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(future=self.schedule.future) end_time = self.loop.time() # error if: given start_at, the job doesn't execute 5 times within 8 seconds. expected_end_time = (start_time + self.interval_in_seconds * (self.count_max - 1) + after_in_seconds) self.assertAlmostEqual(expected_end_time, end_time, places=0)
def _remove_wflow(self, wflow): """ Removes a worflow instance from the list of running instances. """ self._instances.remove(wflow) log.debug('workflow removed from the running list: %s', wflow) try: wflow.result() except asyncio.CancelledError: log.info('Workflow %s has been cancelled', wflow.uid[:8]) except Exception as exc: log.warning('Workflow %s ended on exception', wflow.uid[:8]) log.exception(exc) if self._must_stop and not self._instances and not self.done(): self.set_result(None) log.debug('no more workflow running, engine stopped')
def test_workflow_cancel(self): async def test(): tmpl = TEMPLATES['workflow_cancel'] wflow = Workflow(WorkflowTemplate.from_dict(tmpl)) wflow.run({'initial': 'data'}) # Workflow is cancelled with self.assertRaises(asyncio.CancelledError): await wflow self.assertEqual(FutureState.get(wflow), FutureState.cancelled) # This task was cancelled task = wflow._tasks_by_id.get('cancel') with self.assertRaises(asyncio.CancelledError): task.exception() self.assertEqual(FutureState.get(task), FutureState.cancelled) # These tasks were never started for tid in ('2', '3', '4'): task = wflow._tasks_by_id.get(tid) self.assertIs(task, None) self.loop.run_until_complete(test())
def read_loop(self) -> None: while True: try: await self._read_loop_step() except asyncio.CancelledError: self._shut_down() return except Exception as e: self.__connected.clear() connection_error = ConnectionFailure('Connection was lost due to: {}'.format(str(e))) self.close(error=connection_error) for ft in self.__request_futures.values(): ft.set_exception(connection_error) self.__request_futures = {} try: await self.reconnect() except asyncio.CancelledError: self._shut_down() return
def test_close_cancelling(self): channel = yield from self.create_channel() rpc = yield from RPC.create(channel, auto_delete=True) @asyncio.coroutine def sleeper(): yield from asyncio.sleep(60, loop=self.loop) yield from rpc.register('test.sleeper', sleeper, auto_delete=True) tasks = set() for _ in range(10): tasks.add(self.loop.create_task(rpc.proxy.test.sleeper())) yield from rpc.close() for task in tasks: with self.assertRaises(asyncio.CancelledError): yield from task
def start_polling(self, wait_on_error=60): """Wrapper around self.poll_base_resource() for exception handling.""" while True: try: await self.poll_base_resource() except asyncio.CancelledError: self.logger.info('Polling cancelled') break except asyncio.TimeoutError: self.logger.warning('Polling failed due to TimeoutError') except (APIError, TimeoutError, ClientOSError, ClientResponseError) as e: # log error and start all over again self.logger.warning('Polling failed with a temporary error: {}'.format(e)) except: self.logger.exception('Polling failed with an unexpected exception:') self.action_id = None self.logger.info('Retry will happen in {} seconds'.format( wait_on_error)) await asyncio.sleep(wait_on_error)
def exit_progress(self): while self.coroutines_count > 2: try: self.update_coroutines_count(simple=False) pending = len(db_proc) # Spaces at the end are important, as they clear previously printed # output - \r doesn't clean whole line print( '{} coroutines active, {} DB items pending '.format( self.coroutines_count, pending), end='\r' ) await sleep(.5) except CancelledError: return except Exception as e: self.log.exception('A wild {} appeared in exit_progress!', e.__class__.__name__)
def update_spawns(self, initial=False): while True: try: await run_threaded(spawns.update) LOOP.create_task(run_threaded(spawns.pickle)) except OperationalError as e: self.log.exception('Operational error while trying to update spawns.') if initial: raise OperationalError('Could not update spawns, ensure your DB is set up.') from e await sleep(15, loop=LOOP) except CancelledError: raise except Exception as e: self.log.exception('A wild {} appeared while updating spawns!', e.__class__.__name__) await sleep(15, loop=LOOP) else: break
def bootstrap(self): try: self.log.warning('Starting bootstrap phase 1.') await self.bootstrap_one() except CancelledError: raise except Exception: self.log.exception('An exception occurred during bootstrap phase 1.') try: self.log.warning('Starting bootstrap phase 2.') await self.bootstrap_two() except CancelledError: raise except Exception: self.log.exception('An exception occurred during bootstrap phase 2.') self.log.warning('Starting bootstrap phase 3.') unknowns = list(spawns.unknown) shuffle(unknowns) tasks = (self.try_again(point) for point in unknowns) await gather(*tasks, loop=LOOP) self.log.warning('Finished bootstrapping.')
def fetch(self, point, key=conf.GOOGLE_MAPS_KEY): if not key: return self.fallback() try: async with ClientSession(loop=LOOP) as session: async with session.get( 'https://maps.googleapis.com/maps/api/elevation/json', params={'locations': '{0[0]},{0[1]}'.format(point), 'key': key}, timeout=10) as resp: response = await resp.json(loads=json_loads) altitude = response['results'][0]['elevation'] self.altitudes[point] = altitude self.changed = True return altitude except CancelledError: raise except Exception: try: self.log.error(response['error_message']) except (KeyError, NameError): self.log.error('Error fetching altitude for {}.', point) return self.fallback()
def test_reader(subscription): reader = subscription.get_reader() assert not reader.is_active m = mock.Mock() @reader.callback def callback(channel_name, model): m(model) return False @asyncio.coroutine def go(): listener = yield from reader.listen() assert reader.is_active listener.cancel() with pytest.raises(asyncio.CancelledError): yield from listener assert not reader.is_active assert not m.called yield from reader.manager.stop() assert reader.manager.closed LOOP.run_until_complete(go())
def run(self) -> None: self.logger.info(f"connecting to {self.server}...") reader, writer = await asyncio.open_connection( self.server.host, self.server.port, ssl=self.server.ssl, loop=self.loop ) self.writer = writer await self.queue.put(NetworkEvent('connected', self)) try: while not reader.at_eof(): line = await reader.readline() line = line.strip() self.logger.debug(">", line) if line: event = NetworkEvent(NetworkEventName.RAW_LINE, line) await self.queue.put(event) except asyncio.CancelledError: self.logger.info("Connection.run was cancelled") except ConnectionResetError as e: self.logger.warning(f"connection was reset; {e}") finally: self.close() await self.queue.put(NetworkEvent('disconnected', None))
def read(self, callback: Callable[[bytearray], Any]): try: for downloader in self._downloaders: # Wait until downloader is not in a downloaded/cancelled state. async with self._state_condition: while downloader.state not in (DOWNLOADED, CANCELLED): await self._state_condition.wait() if downloader.state != DOWNLOADED: self._debug('Downloader not in `DOWNLOADED` state, but in `{!s}`.'.format(downloader.state)) raise CancelledError() # Open file and send all its bytes it to back. await read_from_file_by_chunks(downloader.buffer_file_path, callback, self._chunk_size, lambda: self._state != CANCELLED, loop=self._loop) except Exception as exc: raise ReadError(exc)
def close_connection(self): assert self._websocket, "Connection to backend not opened" for task in (self._ws_recv_handler_task, self._watchdog_task): if not task: continue task.cancel() try: await task except (asyncio.CancelledError, websockets.exceptions.ConnectionClosed): pass try: await self._websocket.close() except websockets.exceptions.ConnectionClosed: pass self._websocket = None self._ws_recv_handler_task = None self._watchdog_task = None logger.debug('Connection to backend closed')
def poll(self): """Wait for packets to send to the client.""" try: packets = [await asyncio.wait_for(self.queue.get(), self.server.ping_timeout)] self.queue.task_done() except (asyncio.TimeoutError, asyncio.CancelledError): raise IOError() if packets == [None]: return [] try: packets.append(self.queue.get_nowait()) self.queue.task_done() except asyncio.QueueEmpty: pass return packets
def trigger_event(self, event, *args): """Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed, or if having a single method that catches all events is desired. Note: this method is a coroutine. """ handler_name = 'on_' + event if hasattr(self, handler_name): handler = getattr(self, handler_name) if asyncio.iscoroutinefunction(handler) is True: try: ret = await handler(*args) except asyncio.CancelledError: # pragma: no cover pass else: ret = handler(*args) return ret
def trigger_callback(self, sid, namespace, id, data): """Invoke an application callback. Note: this method is a coroutine. """ callback = None try: callback = self.callbacks[sid][namespace][id] except KeyError: # if we get an unknown callback we just ignore it self.server.logger.warning('Unknown callback received, ignoring.') else: del self.callbacks[sid][namespace][id] if callback is not None: if asyncio.iscoroutinefunction(callback) is True: try: await callback(*data) except asyncio.CancelledError: # pragma: no cover pass else: callback(*data)
def _trigger_event(self, event, namespace, *args): """Invoke an application event handler.""" # first see if we have an explicit handler for the event if namespace in self.handlers and event in self.handlers[namespace]: if asyncio.iscoroutinefunction(self.handlers[namespace][event]) \ is True: try: ret = await self.handlers[namespace][event](*args) except asyncio.CancelledError: # pragma: no cover pass else: ret = self.handlers[namespace][event](*args) return ret # or else, forward the event to a namepsace handler if one exists elif namespace in self.namespace_handlers: return await self.namespace_handlers[namespace].trigger_event( event, *args)
def run(self, arguments, settings, app): if arguments.reload: if not HAS_AUTORELOAD: sys.stderr.write( 'You must install aiohttp_autoreload for the --reload option to work.\n' 'Use `pip install aiohttp_autoreload` to install aiohttp_autoreload.\n' ) return 1 aiohttp_autoreload.start() port = arguments.port or settings.get('address', settings.get('port')) host = arguments.host or settings.get('host', '0.0.0.0') try: web.run_app(app, host=host, port=port, loop=self.get_loop(), access_log_format=settings.get('access_log_format')) except asyncio.CancelledError: # server shut down, we're good here. pass
def load_user_plugins(bot): """loads all user plugins Args: bot: HangupsBot instance """ plugin_list = get_configured_plugins(bot) for module in plugin_list: module_path = "plugins.{}".format(module) try: await load(bot, module_path) except asyncio.CancelledError: raise except: # capture all Exceptions # pylint: disable=bare-except logger.exception(module_path)
def start(self): self.set_state(State.RUN) try: await self._run() except asyncio.CancelledError: self.set_state(State.CANCELED) except Exception as e: self.logger.error("Exception: %s", e, exc_info=True) raise e finally: await self.cleanup() if self._executor is not None: self._executor.shutdown() self.set_state(State.STOP) del self._ALL_TASKS[self._objname]
def run(self): threadless.log.debug("threadlet: %s: tasklet(%s): running", self.threadlet.name, self.name) self.running = True try: value = self.func(self) if isinstance(value, types.GeneratorType): value = yield from value threadless.log.debug("threadlet: %s: tasklet(%s): done", self.threadlet.name, self.name) except asyncio.CancelledError: threadless.log.warn("threadlet: %s: tasklet(%s): cancelled", self.threadlet.name, self.name) except Exception: threadless.log.exception("threadlet: %s: tasklet(%s): exception", self.threadlet.name, self.name) del self.running if self.suspended or self.cancelled: return if self.period and self not in self.threadlet.timeouts: self.schedule(self.period)
def run(self): try: await self.on_run() except asyncio.CancelledError as ex: logger.debug("Connection was closed.") self.set_error(ex) except ProtocolError as ex: logger.debug("Protocol error: %s", ex) self.set_error(ex) except (asyncio.IncompleteReadError, ConnectionError) as ex: logger.debug("Remote end was closed. Terminating connection.") self.set_error(ex) except Exception as ex: logger.exception("Unexpected error. Terminating connection.") self.set_error(ex) finally: self.close()
def open_connection(self): try: server = await asyncio.start_server( self.handle_connection, host=self.host, port=self.port, loop=self.loop, ) try: await server.wait_closed() finally: server.close() await server.wait_closed() except asyncio.CancelledError: raise except Exception: logger.exception( "Unable to start TCP server on %s:%s.", self.host, self.port, )
def open_connection(self): try: server = await start_ipc_server( self.handle_connection, path=self.path, loop=self.loop, ) try: await server.wait_closed() finally: server.close() await server.wait_closed() except asyncio.CancelledError: raise except Exception: logger.exception( "Unable to start UNIX server on %s.", self.path, )
def run(self): while not self.closing: try: result = await self.open_connection() if isinstance(result, ProtocolError) and result.fatal: logger.debug("Fatal error: %s. Not restarting.", result) break except asyncio.CancelledError: break except Exception as ex: logger.debug("Connection error: %r.", ex) else: self.current_backoff_duration = self.min_backoff_duration await asyncio.sleep(self.current_backoff_duration, loop=self.loop) self.current_backoff_duration = min( self.max_backoff_duration, self.current_backoff_duration * 2, )
def test_timeout(loop): canceled_raised = False @asyncio.coroutine def long_running_task(): try: yield from asyncio.sleep(10, loop=loop) except asyncio.CancelledError: nonlocal canceled_raised canceled_raised = True raise with pytest.raises(asyncio.TimeoutError): with timeout(0.01, loop=loop) as t: yield from long_running_task() assert t._loop is loop assert canceled_raised, 'CancelledError was not raised'
def runner(self): self._is_sleep = True try: if self._sleep_start: await asyncio.sleep(self._sleep_start, loop=self.loop) while True: if self._crontab is not None: await asyncio.sleep(self._crontab.next(), loop=self.loop) try: await self.work() except asyncio.CancelledError: raise except BaseException: self.counter['error'] += 1 self.logger.exception('ERROR {} {}'.format( self.name, self.config.get('run', type(self)), )) self._is_sleep = True if not self._persist: return if self._sleep: await asyncio.sleep(self._sleep, loop=self.loop) finally: self._stopped_at = datetime.datetime.now()
def _gen(self, fyield=None, fsend=None): agen = self.get_source_agen() send_value = None try: while True: value = await agen.asend(send_value) if fyield is not None: value = await self._exec_possible_awaitable(fyield, value) send_value = yield value if fsend and send_value is not None: send_value = await self._exec_possible_awaitable(fsend, send_value) except StopAsyncIteration: pass except asyncio.CancelledError: pass finally: self._agen = None
def _run(self): send_value = None try: agen = self.get_source_agen() self.started.set_result(None) except Exception as e: self.started.set_exception(e) try: while True: value = await agen.asend(send_value) send_value = await self._destination(value) except StopAsyncIteration: pass except asyncio.CancelledError: await agen.aclose() except Exception: logger.exception('Error in agen stream') raise finally: self.active = False