本文整理匯總了Python中asyncio.Handle方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.Handle方法的具體用法?Python asyncio.Handle怎麽用?Python asyncio.Handle使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類asyncio
的用法示例。
在下文中一共展示了asyncio.Handle方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: timerEvent
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def timerEvent(self, event): # noqa: N802
timerid = event.timerId()
self._logger.debug("Timer event on id {0}".format(timerid))
if self._stopped:
self._logger.debug("Timer stopped, killing {}".format(timerid))
self.killTimer(timerid)
del self.__callbacks[timerid]
else:
try:
handle = self.__callbacks[timerid]
except KeyError as e:
self._logger.debug(str(e))
pass
else:
if handle._cancelled:
self._logger.debug("Handle {} cancelled".format(handle))
else:
self._logger.debug("Calling handle {}".format(handle))
handle._run()
finally:
del self.__callbacks[timerid]
handle = None
self.killTimer(timerid)
示例2: run_in_executor
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def run_in_executor(self, executor, callback, *args):
"""Run callback in executor.
If no executor is provided, the default executor will be used, which defers execution to
a background thread.
"""
self._logger.debug('Running callback {} with args {} in executor'.format(callback, args))
if isinstance(callback, asyncio.Handle):
assert not args
assert not isinstance(callback, asyncio.TimerHandle)
if callback._cancelled:
f = asyncio.Future()
f.set_result(None)
return f
callback, args = callback.callback, callback.args
if executor is None:
self._logger.debug('Using default executor')
executor = self.__default_executor
if executor is None:
self._logger.debug('Creating default executor')
executor = self.__default_executor = QThreadExecutor()
return asyncio.wrap_future(executor.submit(callback, *args))
示例3: test_callback_with_exception
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_callback_with_exception(self):
def callback():
raise ValueError()
self.loop = mock.Mock()
self.loop.call_exception_handler = mock.Mock()
h = asyncio.Handle(callback, (), self.loop)
h._run()
self.loop.call_exception_handler.assert_called_with({
'message': test_utils.MockPattern('Exception in callback.*'),
'exception': mock.ANY,
'handle': h,
'source_traceback': h._source_traceback,
})
示例4: test_run_once_in_executor_plain
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_run_once_in_executor_plain(self):
def cb():
pass
h = asyncio.Handle(cb, (), self.loop)
f = asyncio.Future(loop=self.loop)
executor = mock.Mock()
executor.submit.return_value = f
self.loop.set_default_executor(executor)
res = self.loop.run_in_executor(None, h)
self.assertIs(f, res)
executor = mock.Mock()
executor.submit.return_value = f
res = self.loop.run_in_executor(executor, h)
self.assertIs(f, res)
self.assertTrue(executor.submit.called)
f.cancel() # Don't complain about abandoned Future.
示例5: test_fail_on_original_selector_callback
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_fail_on_original_selector_callback(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
with unittest.mock.patch.object(loop, "_selector") as mock:
class TestCase(asynctest.TestCase):
use_default_loop = True
def runTest(self):
# add a dummy event
handle = asyncio.Handle(lambda: None, (), self.loop)
key = selectors.SelectorKey(1, 1, selectors.EVENT_READ,
(handle, None))
mock.get_map.return_value = {1: key}
with self.assertRaisesRegex(AssertionError,
"some events watched during the "
"tests were not removed"):
TestCase().debug()
finally:
loop.close()
asyncio.set_event_loop(None)
示例6: test_handle_repr_debug
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle_repr_debug(self):
self.loop.get_debug.return_value = True
# simple function
create_filename = __file__
create_lineno = sys._getframe().f_lineno + 1
h = asyncio.Handle(noop, (1, 2), self.loop)
filename, lineno = test_utils.get_function_source(noop)
self.assertEqual(repr(h),
'<Handle noop(1, 2) at %s:%s created at %s:%s>'
% (filename, lineno, create_filename, create_lineno))
# cancelled handle
h.cancel()
self.assertEqual(
repr(h),
'<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>'
% (filename, lineno, create_filename, create_lineno))
# double cancellation won't overwrite _repr
h.cancel()
self.assertEqual(
repr(h),
'<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>'
% (filename, lineno, create_filename, create_lineno))
示例7: __init__
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def __init__(self, name, tag, *args, prefix=None, untagged_resp_name=None, loop=None, timeout=None):
self.name = name
self.tag = tag
self.args = args
self.prefix = prefix + ' ' if prefix else None
self.untagged_resp_name = untagged_resp_name or name
self.response = None
self._exception = None
self._loop = loop if loop is not None else get_running_loop()
self._event = asyncio.Event(loop=self._loop)
self._timeout = timeout
self._timer = asyncio.Handle(lambda: None, None, self._loop) # fake timer
self._set_timer()
self._literal_data = None
self._expected_size = 0
示例8: call_later
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def call_later(self, delay, callback, *args, context=None):
"""Register callback to be invoked after a certain delay."""
if asyncio.iscoroutinefunction(callback):
raise TypeError("coroutines cannot be used with call_later")
if not callable(callback):
raise TypeError('callback must be callable: {}'.format(type(callback).__name__))
self._logger.debug(
'Registering callback {} to be invoked with arguments {} after {} second(s)'
.format(callback, args, delay))
if sys.version_info >= (3, 7):
return self._add_callback(asyncio.Handle(callback, args, self, context=context), delay)
return self._add_callback(asyncio.Handle(callback, args, self), delay)
示例9: default_exception_handler
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def default_exception_handler(self, context):
"""Handle exceptions.
This is the default exception handler.
This is called when an exception occurs and no exception
handler is set, and can be called by a custom exception
handler that wants to defer to the default behavior.
context parameter has the same meaning as in
`call_exception_handler()`.
"""
self._logger.debug('Default exception handler executing')
message = context.get('message')
if not message:
message = 'Unhandled exception in event loop'
try:
exception = context['exception']
except KeyError:
exc_info = False
else:
exc_info = (type(exception), exception, exception.__traceback__)
log_lines = [message]
for key in [k for k in sorted(context) if k not in {'message', 'exception'}]:
log_lines.append('{}: {!r}'.format(key, context[key]))
self.__log_error('\n'.join(log_lines), exc_info=exc_info)
示例10: test_handle
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle(self):
def callback(*args):
return args
args = ()
h = asyncio.Handle(callback, args, self.loop)
self.assertIs(h._callback, callback)
self.assertIs(h._args, args)
self.assertFalse(h._cancelled)
h.cancel()
self.assertTrue(h._cancelled)
示例11: test_handle_from_handle
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle_from_handle(self):
def callback(*args):
return args
h1 = asyncio.Handle(callback, (), loop=self.loop)
self.assertRaises(
AssertionError, asyncio.Handle, h1, (), self.loop)
示例12: test_handle_weakref
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle_weakref(self):
wd = weakref.WeakValueDictionary()
h = asyncio.Handle(lambda: None, (), self.loop)
wd['h'] = h # Would fail without __weakref__ slot.
示例13: test_handle_repr
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle_repr(self):
self.loop.get_debug.return_value = False
# simple function
h = asyncio.Handle(noop, (1, 2), self.loop)
filename, lineno = test_utils.get_function_source(noop)
self.assertEqual(repr(h),
'<Handle noop(1, 2) at %s:%s>'
% (filename, lineno))
# cancelled handle
h.cancel()
self.assertEqual(repr(h),
'<Handle cancelled>')
# decorated function
cb = asyncio.coroutine(noop)
h = asyncio.Handle(cb, (), self.loop)
self.assertEqual(repr(h),
'<Handle noop() at %s:%s>'
% (filename, lineno))
# partial function
cb = functools.partial(noop, 1, 2)
h = asyncio.Handle(cb, (3,), self.loop)
regex = (r'^<Handle noop\(1, 2\)\(3\) at %s:%s>$'
% (re.escape(filename), lineno))
self.assertRegex(repr(h), regex)
# partial method
if sys.version_info >= (3, 4):
method = HandleTests.test_handle_repr
cb = functools.partialmethod(method)
filename, lineno = test_utils.get_function_source(method)
h = asyncio.Handle(cb, (), self.loop)
cb_regex = r'<function HandleTests.test_handle_repr .*>'
cb_regex = (r'functools.partialmethod\(%s, , \)\(\)' % cb_regex)
regex = (r'^<Handle %s at %s:%s>$'
% (cb_regex, re.escape(filename), lineno))
self.assertRegex(repr(h), regex)
示例14: test_timer_comparison
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_timer_comparison(self):
def callback(*args):
return args
when = time.monotonic()
h1 = asyncio.TimerHandle(when, callback, (), self.loop)
h2 = asyncio.TimerHandle(when, callback, (), self.loop)
# TODO: Use assertLess etc.
self.assertFalse(h1 < h2)
self.assertFalse(h2 < h1)
self.assertTrue(h1 <= h2)
self.assertTrue(h2 <= h1)
self.assertFalse(h1 > h2)
self.assertFalse(h2 > h1)
self.assertTrue(h1 >= h2)
self.assertTrue(h2 >= h1)
self.assertTrue(h1 == h2)
self.assertFalse(h1 != h2)
h2.cancel()
self.assertFalse(h1 == h2)
h1 = asyncio.TimerHandle(when, callback, (), self.loop)
h2 = asyncio.TimerHandle(when + 10.0, callback, (), self.loop)
self.assertTrue(h1 < h2)
self.assertFalse(h2 < h1)
self.assertTrue(h1 <= h2)
self.assertFalse(h2 <= h1)
self.assertFalse(h1 > h2)
self.assertTrue(h2 > h1)
self.assertFalse(h1 >= h2)
self.assertTrue(h2 >= h1)
self.assertFalse(h1 == h2)
self.assertTrue(h1 != h2)
h3 = asyncio.Handle(callback, (), self.loop)
self.assertIs(NotImplemented, h1.__eq__(h3))
self.assertIs(NotImplemented, h1.__ne__(h3))
示例15: test_handle_signal_cancelled_handler
# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import Handle [as 別名]
def test_handle_signal_cancelled_handler(self):
h = asyncio.Handle(mock.Mock(), (),
loop=mock.Mock())
h.cancel()
self.loop._signal_handlers[signal.NSIG + 1] = h
self.loop.remove_signal_handler = mock.Mock()
self.loop._handle_signal(signal.NSIG + 1)
self.loop.remove_signal_handler.assert_called_with(signal.NSIG + 1)