本文整理汇总了Python中asyncio.InvalidStateError方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.InvalidStateError方法的具体用法?Python asyncio.InvalidStateError怎么用?Python asyncio.InvalidStateError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.InvalidStateError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: future_set_exception_unless_cancelled
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def future_set_exception_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", exc: BaseException
) -> None:
"""Set the given ``exc`` as the `Future`'s exception.
If the Future is already canceled, logs the exception instead. If
this logging is not desired, the caller should explicitly check
the state of the Future and call ``Future.set_exception`` instead of
this wrapper.
Avoids ``asyncio.InvalidStateError`` when calling ``set_exception()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 6.0
"""
if not future.cancelled():
future.set_exception(exc)
else:
app_log.error("Exception after Future was cancelled", exc_info=exc)
示例2: future_set_exc_info
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def future_set_exc_info(
future: "Union[futures.Future[_T], Future[_T]]",
exc_info: Tuple[
Optional[type], Optional[BaseException], Optional[types.TracebackType]
],
) -> None:
"""Set the given ``exc_info`` as the `Future`'s exception.
Understands both `asyncio.Future` and the extensions in older
versions of Tornado to enable better tracebacks on Python 2.
.. versionadded:: 5.0
.. versionchanged:: 6.0
If the future is already cancelled, this function is a no-op.
(previously ``asyncio.InvalidStateError`` would be raised)
"""
if exc_info[1] is None:
raise Exception("future_set_exc_info called with no exception")
future_set_exception_unless_cancelled(future, exc_info[1])
示例3: get_transport
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def get_transport(self, transport: str) -> ClientTransport:
"""Look up initialized client transport methods.
Args:
transport: Name of the transport.
Returns:
A :class:`ClientTransport` NamedTuple for the specified transport.
Raises:
KeyError: If the specified transport was not provided when calling
:meth:`__init__`.
asyncio.InvalidStateError: If PT has not yet started, or if the
transport is not yet initialized.
RuntimeError: If the PT returned an error while initializing the
specified transport.
"""
self._check_running()
return self._transports[transport].result()
示例4: _ping_interval
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _ping_interval(self):
while True:
await asyncio.sleep(self.options["ping_interval"], loop=self._loop)
if not self.is_connected:
continue
try:
self._pings_outstanding += 1
if self._pings_outstanding > self.options[
"max_outstanding_pings"]:
await self._process_op_err(ErrStaleConnection)
return
await self._send_ping()
except asyncio.CancelledError:
break
# except asyncio.InvalidStateError:
# pass
示例5: _complete_future
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _complete_future(self, ray_object_id):
# TODO(ilr): Consider race condition between popping from the
# waiting_dict and as_future appending to the waiting_dict's list.
logger.debug(
"Completing plasma futures for object id {}".format(ray_object_id))
if ray_object_id not in self._waiting_dict:
return
obj = self._worker.get_objects([ray_object_id], timeout=0)[0]
futures = self._waiting_dict.pop(ray_object_id)
for fut in futures:
try:
fut.set_result(obj)
except asyncio.InvalidStateError:
# Avoid issues where process_notifications
# and check_immediately both get executed
logger.debug("Failed to set result for future {}."
"Most likely already set.".format(fut))
示例6: test_exception
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def test_exception(self):
exc = RuntimeError()
f = asyncio.Future(loop=self.loop)
self.assertRaises(asyncio.InvalidStateError, f.exception)
# StopIteration cannot be raised into a Future - CPython issue26221
self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised",
f.set_exception, StopIteration)
f.set_exception(exc)
self.assertFalse(f.cancelled())
self.assertTrue(f.done())
self.assertRaises(RuntimeError, f.result)
self.assertEqual(f.exception(), exc)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())
示例7: test_exception
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def test_exception(self):
exc = RuntimeError()
f = self._new_future(loop=self.loop)
self.assertRaises(asyncio.InvalidStateError, f.exception)
# StopIteration cannot be raised into a Future - CPython issue26221
self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised",
f.set_exception, StopIteration)
f.set_exception(exc)
self.assertFalse(f.cancelled())
self.assertTrue(f.done())
self.assertRaises(RuntimeError, f.result)
self.assertEqual(f.exception(), exc)
self.assertRaises(asyncio.InvalidStateError, f.set_result, None)
self.assertRaises(asyncio.InvalidStateError, f.set_exception, None)
self.assertFalse(f.cancel())
示例8: _set_reply
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _set_reply(self, correlation_id, msg):
if correlation_id in self._futures:
try:
self._futures[correlation_id].set_result(msg)
except asyncio.InvalidStateError as e:
LOGGER.error(
'Attempting to set result on already-resolved future: %s',
str(e))
示例9: _fail_reply
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _fail_reply(self, correlation_id, err):
if correlation_id in self._futures and \
not self._futures[correlation_id].done():
try:
self._futures[correlation_id].set_exception(err)
except asyncio.InvalidStateError as e:
LOGGER.error(
'Attempting to set exception on already-resolved future: '
'%s',
str(e))
示例10: future_set_result_unless_cancelled
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def future_set_result_unless_cancelled(
future: "Union[futures.Future[_T], Future[_T]]", value: _T
) -> None:
"""Set the given ``value`` as the `Future`'s result, if not cancelled.
Avoids ``asyncio.InvalidStateError`` when calling ``set_result()`` on
a cancelled `asyncio.Future`.
.. versionadded:: 5.0
"""
if not future.cancelled():
future.set_result(value)
示例11: _check_not_started
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _check_not_started(self) -> None:
if self._process:
raise asyncio.InvalidStateError('PT has already started')
示例12: _check_started
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _check_started(self) -> None:
if not self._process:
raise asyncio.InvalidStateError('PT has not yet started')
示例13: _check_running
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _check_running(self) -> None:
self._check_started()
if self._stopping:
raise asyncio.InvalidStateError('PT is stopping or has stopped')
示例14: cancel_awaitable
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def cancel_awaitable(
awaitable: Awaitable[Any],
log: Logger,
done_cb: Optional[Callable[[Awaitable[Any]], Any]] = None
) -> None:
"""
Cancel a coroutine or a :class:`asyncio.Task`.
Arguments:
- `coroutine_or_task`: The coroutine or
:class:`asyncio.Task` to be cancelled.
- `done_cb`: An optional callback to be called once the task
has been cancelled. Will be called immediately if
`coroutine_or_task` is a coroutine.
"""
if asyncio.iscoroutine(awaitable):
coroutine = cast(Coroutine[Any, Any, None], awaitable)
log.debug('Closing coroutine {}', coroutine)
coroutine.close()
if done_cb is not None:
done_cb(coroutine)
else:
task = cast('asyncio.Task[None]', awaitable)
# A cancelled task can still contain an exception, so we try to
# fetch that first to avoid having the event loop's exception
# handler yelling at us.
try:
exc = task.exception()
except asyncio.CancelledError:
log.debug('Already cancelled task {}', task)
except asyncio.InvalidStateError:
log.debug('Cancelling task {}', task)
task.cancel()
else:
if exc is not None:
log.debug('Ignoring completion of task {} with {}', task, task.result())
else:
log.debug('Ignoring exception of task {}: {}', task, repr(exc))
if done_cb is not None:
# noinspection PyTypeChecker
task.add_done_callback(done_cb)
示例15: _task_done_handler
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import InvalidStateError [as 别名]
def _task_done_handler(self, task: 'asyncio.Task[None]') -> None:
assert self._tasks is not None
self._tasks_remaining -= 1
self._log.debug('Task done (#tasks={}, #running={}), {}',
len(self._tasks), self._tasks_remaining, task)
# A cancelled task can still contain an exception, so we try to
# fetch that first to avoid having the event loop's exception
# handler yelling at us.
try:
exc = task.exception()
except asyncio.CancelledError:
# We don't care about cancelled tasks unless it's the last one and no
# exception has been set.
self._log.debug('Task was cancelled')
if self._tasks_remaining == 0 and not self._have_result:
error = 'All tasks have been cancelled prior to an exception'
self._set_result(Result(InternalError(error)))
self._cancelled = True
return
except asyncio.InvalidStateError as exc_:
# Err... what the... ?
self._log.exception('Task done but not done... what the...', exc_)
exc = exc_
# Tasks may not ever return without an exception
if exc is None:
result = task.result()
exc = InternalError('Task returned unexpectedly with {}: {}'.format(
type(result), result))
# Store the result and cancel all running tasks
self._set_result(Result(exc))
self._cancel()