本文整理汇总了Python中concurrent.futures.CancelledError方法的典型用法代码示例。如果您正苦于以下问题:Python futures.CancelledError方法的具体用法?Python futures.CancelledError怎么用?Python futures.CancelledError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类concurrent.futures
的用法示例。
在下文中一共展示了futures.CancelledError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _do_heartbeat
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def _do_heartbeat(self):
while True:
try:
if self._socket.getsockopt(zmq.TYPE) == zmq.ROUTER:
yield from self._do_router_heartbeat()
elif self._socket.getsockopt(zmq.TYPE) == zmq.DEALER:
yield from self._do_dealer_heartbeat()
yield from asyncio.sleep(self._heartbeat_interval,
loop=self._event_loop)
except CancelledError: # pylint: disable=try-except-raise
# The concurrent.futures.CancelledError is caught by asyncio
# when the Task associated with the coroutine is cancelled.
# The raise is required to stop this component.
raise
except Exception as e: # pylint: disable=broad-except
LOGGER.exception(
"An error occurred while sending heartbeat: %s", e)
示例2: wait
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
"""Block until the internal flag is true.
Returns an awaitable, which raises `tornado.util.TimeoutError` after a
timeout.
"""
fut = Future() # type: Future[None]
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_callback(lambda fut: self._waiters.remove(fut))
if timeout is None:
return fut
else:
timeout_fut = gen.with_timeout(
timeout, fut, quiet_exceptions=(CancelledError,)
)
# This is a slightly clumsy workaround for the fact that
# gen.with_timeout doesn't cancel its futures. Cancelling
# fut will remove it from the waiters list.
timeout_fut.add_done_callback(
lambda tf: fut.cancel() if not fut.done() else None
)
return timeout_fut
示例3: test_recv_json_cancelled
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def test_recv_json_cancelled(self):
@asyncio.coroutine
def test():
a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
f = b.recv_json()
assert not f.done()
f.cancel()
# cycle eventloop to allow cancel events to fire
yield from asyncio.sleep(0)
obj = dict(a=5)
yield from a.send_json(obj)
with pytest.raises(CancelledError):
recvd = yield from f
assert f.done()
# give it a chance to incorrectly consume the event
events = yield from b.poll(timeout=5)
assert events
yield from asyncio.sleep(0)
# make sure cancelled recv didn't eat up event
f = b.recv_json()
recvd = yield from asyncio.wait_for(f, timeout=5)
assert recvd == obj
self.loop.run_until_complete(test())
示例4: run
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def run(self):
while not self.closed:
try:
segment, future = self.futures.get(block=True, timeout=0.5)
except queue.Empty:
continue
# End of stream
if future is None:
break
while not self.closed:
try:
result = future.result(timeout=0.5)
except futures.TimeoutError:
continue
except futures.CancelledError:
break
if result is not None:
self.write(segment, result)
break
self.close()
示例5: wait
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def wait(self, timeout=None):
"""Block until the internal flag is true.
Returns a Future, which raises `tornado.util.TimeoutError` after a
timeout.
"""
fut = Future()
if self._value:
fut.set_result(None)
return fut
self._waiters.add(fut)
fut.add_done_callback(lambda fut: self._waiters.remove(fut))
if timeout is None:
return fut
else:
timeout_fut = gen.with_timeout(timeout, fut, quiet_exceptions=(CancelledError,))
# This is a slightly clumsy workaround for the fact that
# gen.with_timeout doesn't cancel its futures. Cancelling
# fut will remove it from the waiters list.
timeout_fut.add_done_callback(lambda tf: fut.cancel() if not fut.done() else None)
return timeout_fut
示例6: test_server
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def test_server(self):
host = "0.0.0.0"
port = 5489
socket_timeout = 60
def timeout_server():
# need a more robust mechanism for when to cancel the future
time.sleep(2)
self.stop_server_future.cancel()
thread = threading.Thread(target=timeout_server)
thread.daemon = True
thread.start()
with self.assertRaises(CancelledError):
start_server(host=host, port=port,
loop=self.loop,
socket_timeout=socket_timeout,
stop_server_future=self.stop_server_future)
示例7: start_login
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def start_login(self, request: web.Request) -> web.Response:
user_id = self.verify_token(request)
manual = request.query.get("manual")
if manual and (manual == "1" or manual.lower() == "true"):
manual = True
else:
manual = False
user = u.User.get_by_mxid(user_id)
if user.client:
return web.json_response({
"status": "success",
"name": await user.name_future,
})
try:
return web.json_response(self.ongoing[user.mxid].current_status)
except KeyError:
pass
login = WebCredentialsPrompt(self, user, manual, self.device_name, self.loop)
self.ongoing[user.mxid] = login
try:
return web.json_response(await login.start())
except asyncio.CancelledError:
raise ErrorResponse(410, "Login cancelled", "HANGOUTS_LOGIN_CANCELLED")
示例8: _receive_credential
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def _receive_credential(self, result_type: CredentialType) -> Optional[str]:
if self.cancelled:
return None
self.current_status = {
"next_step": result_type.value,
}
if result_type == CredentialType.AUTHORIZATION:
self.current_status["manual_auth_url"] = make_login_url(self.device_name)
try:
return self.queue.send_to_async(self.current_status,
lambda: self._set_expecting(result_type))
except futures.TimeoutError:
self.cancel()
return None
except futures.CancelledError:
return None
示例9: serve_forever
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def serve_forever(self):
if self._serving_forever_fut is not None:
raise RuntimeError(
f'server {self!r} is already being awaited on serve_forever()')
if self._sockets is None:
raise RuntimeError(f'server {self!r} is closed')
self._start_serving()
self._serving_forever_fut = self._loop.create_future()
try:
await self._serving_forever_fut
except futures.CancelledError:
try:
self.close()
await self.wait_closed()
finally:
raise
finally:
self._serving_forever_fut = None
示例10: start
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def start(self):
try:
if not self.isConnected():
await self._connect()
while self.isConnected():
await self.client.parse()
except CancelledError:
pass
except Exception as err:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
log.info("FICSConnection.run: %s" % repr(err),
extra={"task": (self.host, "raw")})
self.close()
if isinstance(err,
(IOError, LogOnException, EOFError, socket.error,
socket.gaierror, socket.herror)):
self.emit("error", err)
else:
raise
finally:
if isinstance(self, FICSMainConnection):
self.emit("disconnected")
示例11: submit
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def submit(self, label, command, opts):
"""Submit a bgutil command to run it asynchronously."""
task = BgUtilTask(label, datetime.now())
self.tasks.append(task)
def _done_callback(f):
try:
result = f.result()
task.completed(result)
except futures.CancelledError as e:
task.cancelled(e)
except futures.TimeoutError as e:
task.timed_out(e)
except Exception as e:
task.failed(e)
future = self._executor.submit(
self._wrap_command, task, context.accessor, command, opts
)
task.submitted()
future.add_done_callback(_done_callback)
示例12: wait
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def wait(self, _timeout=None):
if self._awaited:
try:
self._future.result(timeout=_timeout)
except FutureTimeoutError:
self.set_timedout()
except FutureCancelledError:
self.cancel()
return self
示例13: test_CancellableFuture_can_be_cancelled_while_it_is_running
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def test_CancellableFuture_can_be_cancelled_while_it_is_running(observer_runner):
from concurrent.futures import ThreadPoolExecutor, CancelledError
from moler.runner import CancellableFuture
# concurrent.futures.Future can't cancel() while it is already running
stop_running = threading.Event()
is_done = threading.Event()
def activity(stop_running, is_done):
while not stop_running.is_set():
time.sleep(0.5)
is_done.set()
future = ThreadPoolExecutor().submit(activity, stop_running, is_done)
observer_lock = threading.Lock()
c_future = CancellableFuture(future, observer_lock, stop_running, is_done)
try:
time.sleep(0.1) # allow threads switch to ensure future running
assert c_future.running()
cancelled = c_future.cancel()
time.sleep(0.1) # allow threads switch
assert not c_future.running()
assert is_done.is_set()
assert cancelled is True
assert c_future.cancelled()
assert c_future.done()
with pytest.raises(CancelledError):
c_future.result()
except AssertionError:
raise
finally:
stop_running.set()
# --------------------------- resources ---------------------------
示例14: run_tasks
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def run_tasks(self):
""" Run the tasks attached to the instance """
tasks = self.get_tasks()
self._gathered_tasks = asyncio.gather(*tasks, loop=self.loop)
try:
await self._gathered_tasks
except CancelledError:
pass
示例15: _remove_expired_futures
# 需要导入模块: from concurrent import futures [as 别名]
# 或者: from concurrent.futures import CancelledError [as 别名]
def _remove_expired_futures(self):
while True:
try:
yield from asyncio.sleep(self._connection_timeout,
loop=self._event_loop)
self._futures.remove_expired()
except CancelledError: # pylint: disable=try-except-raise
# The concurrent.futures.CancelledError is caught by asyncio
# when the Task associated with the coroutine is cancelled.
# The raise is required to stop this component.
raise
except Exception as e: # pylint: disable=broad-except
LOGGER.exception("An error occurred while"
" cleaning up expired futures: %s",
e)