本文整理汇总了Python中asyncio.async方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.async方法的具体用法?Python asyncio.async怎么用?Python asyncio.async使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.async方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_active
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def set_active(self):
"""Activate conversation tab"""
settings = QtCore.QSettings()
# Set the client as active
if settings.value("send_client_active", True, type=bool):
future = asyncio.async(self.client.set_active())
future.add_done_callback(lambda future: future.result())
# Mark the newest event as read
if settings.value("send_read_state", True, type=bool):
future = asyncio.async(self.conv.update_read_timestamp())
future.add_done_callback(lambda future: future.result())
self.num_unread_local = 0
self.set_title()
self.messageTextEdit.setFocus()
示例2: test_kv_missing
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_kv_missing(self, loop, consul_port):
c = consul.aio.Consul(port=consul_port, loop=loop)
@asyncio.coroutine
def main():
fut = asyncio.async(put(), loop=loop)
yield from c.kv.put('index', 'bump')
index, data = yield from c.kv.get('foo')
assert data is None
index, data = yield from c.kv.get('foo', index=index)
assert data['Value'] == six.b('bar')
yield from fut
c.close()
@asyncio.coroutine
def put():
yield from asyncio.sleep(2.0/100, loop=loop)
yield from c.kv.put('foo', 'bar')
loop.run_until_complete(main())
示例3: test_kv_subscribe
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_kv_subscribe(self, loop, consul_port):
c = consul.aio.Consul(port=consul_port, loop=loop)
@asyncio.coroutine
def get():
fut = asyncio.async(put(), loop=loop)
index, data = yield from c.kv.get('foo')
assert data is None
index, data = yield from c.kv.get('foo', index=index)
assert data['Value'] == six.b('bar')
yield from fut
c.close()
@asyncio.coroutine
def put():
yield from asyncio.sleep(1.0/100, loop=loop)
response = yield from c.kv.put('foo', 'bar')
assert response is True
loop.run_until_complete(get())
示例4: client_connected_handler
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def client_connected_handler(self, client_reader, client_writer):
remote_conn_info = client_writer.get_extra_info("peername")
local_conn_info = client_writer.get_extra_info("sockname")
SID = self.add_session(remote_conn_info, local_conn_info, stype="asyncio_session")
# Start a new asyncio.Task to handle this specific client connection
task = asyncio.async(self.handle_client(SID, client_reader, client_writer))
def client_done(SID, _):
# When the tasks that handles the specific client connection is done
client_writer.close()
self.remove_session(SID)
# Add the client_done callback to be run when the future becomes done
task.add_done_callback(functools.partial(client_done, SID))
示例5: run
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def run():
mp = None
if config["MAIL"]["START_MAILER"]:
mp = Popen(['python3', mailer])
try:
start_server = websockets.serve(server.server, config["SERVER"]["INTERFACE"], config["SERVER"]["PORT"])
if config["SERVER"]["RELOAD_ON_CHANGE"]:
asyncio.async(reloader(mp))
loop = asyncio.get_event_loop()
asyncio.async(start_server)
if config["IPN"]["START_IPN_SERVER"]:
asyncio.async(ipn.init(loop))
ext = config["SERVER"].get("EXT", None)
if ext is not None:
load_extensions(ext)
loop.run_forever()
finally:
if mp is not None:
mp.terminate()
示例6: __call__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def __call__(self):
self.logger = CronService.resolve("moxie.cores.log.LogService")
self.run = CronService.resolve("moxie.cores.run.RunService")
self.database = CronService.resolve("moxie.cores.database.DatabaseService")
while True:
jobs = (yield from self.database.job.list(
Job.manual == False,
Job.scheduled <= (
dt.datetime.utcnow() +
dt.timedelta(seconds=self.HEARTBEAT))
))
# yield from self.logger.log("cron", "Wakeup")
for job in jobs:
asyncio.async(self.handle(job))
# yield from self.logger.log("cron", "Sleep")
yield from asyncio.sleep(self.HEARTBEAT)
示例7: test_create_task
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_create_task(self):
class MyTask(asyncio.Task):
pass
@asyncio.coroutine
def test():
pass
class EventLoop(base_events.BaseEventLoop):
def create_task(self, coro):
return MyTask(coro, loop=loop)
loop = EventLoop()
self.set_event_loop(loop)
coro = test()
task = asyncio.async(coro, loop=loop)
self.assertIsInstance(task, MyTask)
# make warnings quiet
task._log_destroy_pending = False
coro.close()
示例8: test_async_coroutine
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_async_coroutine(self):
@asyncio.coroutine
def notmuch():
return 'ok'
t = asyncio.async(notmuch(), loop=self.loop)
self.loop.run_until_complete(t)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
self.assertIs(t._loop, self.loop)
loop = asyncio.new_event_loop()
self.set_event_loop(loop)
t = asyncio.async(notmuch(), loop=loop)
self.assertIs(t._loop, loop)
loop.run_until_complete(t)
loop.close()
示例9: test_async_task
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_async_task(self):
@asyncio.coroutine
def notmuch():
return 'ok'
t_orig = asyncio.Task(notmuch(), loop=self.loop)
t = asyncio.async(t_orig)
self.loop.run_until_complete(t)
self.assertTrue(t.done())
self.assertEqual(t.result(), 'ok')
self.assertIs(t, t_orig)
loop = asyncio.new_event_loop()
self.set_event_loop(loop)
with self.assertRaises(ValueError):
t = asyncio.async(t_orig, loop=loop)
loop.close()
t = asyncio.async(t_orig, loop=self.loop)
self.assertIs(t, t_orig)
示例10: test_shield_effect
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
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)
示例11: test_exception_marking
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def test_exception_marking(self):
# Test for the first line marked "Mark exception retrieved."
@asyncio.coroutine
def inner(f):
yield from f
raise RuntimeError('should not be ignored')
a = asyncio.Future(loop=self.one_loop)
b = asyncio.Future(loop=self.one_loop)
@asyncio.coroutine
def outer():
yield from asyncio.gather(inner(a), inner(b), loop=self.one_loop)
f = asyncio.async(outer(), loop=self.one_loop)
test_utils.run_briefly(self.one_loop)
a.set_result(None)
test_utils.run_briefly(self.one_loop)
b.set_result(None)
test_utils.run_briefly(self.one_loop)
self.assertIsInstance(f.exception(), RuntimeError)
示例12: wait_for_new_message
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def wait_for_new_message(host, user, password):
imap_client = aioimaplib.IMAP4_SSL(host=host)
yield from imap_client.wait_hello_from_server()
yield from imap_client.login(user, password)
yield from imap_client.select()
asyncio.async(imap_client.idle())
while True:
msg = yield from imap_client.wait_server_push()
print('--> received from server: %s' % msg)
if 'EXISTS' in msg:
imap_client.idle_done()
break
yield from imap_client.logout()
示例13: run
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def run(self):
print("Starting CPU solver")
s = Solver()
while self.job == None or self.nonce1 == None:
time.sleep(2)
print(".", end='', flush=True)
while not self._stop:
nonce2 = self.increase_nonce()
nonce2 = nonce2.rjust(32 - len(self.nonce1) - len(self.solver_nonce), b'\0')
header = self.job.build_header(self.nonce1 + self.solver_nonce + nonce2)
sol_cnt = s.find_solutions(header)
self.counter(sol_cnt) # Increase counter for stats
for i in range(sol_cnt):
solution = b'\xfd\x40\x05' + s.get_solution(i)
if self.job.is_valid(header, solution, self.job.target):
print("FOUND VALID SOLUTION!")
# asyncio.run_coroutine_threadsafe(self.on_share(self.job, self.solver_nonce + nonce2, solution), self.loop)
asyncio.async(self.on_share(self.job, self.solver_nonce + nonce2, solution), loop=self.loop)
示例14: deliver_message
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def deliver_message(self, timeout=None):
"""
Deliver next received message.
Deliver next message received from the broker. If no message is available, this methods waits until next message arrives or ``timeout`` occurs.
This method is a *coroutine*.
:param timeout: maximum number of seconds to wait before returning. If timeout is not specified or None, there is no limit to the wait time until next message arrives.
:return: instance of :class:`hbmqtt.session.ApplicationMessage` containing received message information flow.
:raises: :class:`asyncio.TimeoutError` if timeout occurs before a message is delivered
"""
deliver_task = ensure_future(self._handler.mqtt_deliver_next_message(), loop=self._loop)
self.client_tasks.append(deliver_task)
self.logger.debug("Waiting message delivery")
done, pending = yield from asyncio.wait([deliver_task], loop=self._loop, return_when=asyncio.FIRST_EXCEPTION, timeout=timeout)
if deliver_task in done:
self.client_tasks.pop()
return deliver_task.result()
else:
#timeout occured before message received
deliver_task.cancel()
raise asyncio.TimeoutError
示例15: hello_world
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import async [as 别名]
def hello_world():
yield from asyncio.sleep(1)
print('Hello World')
asyncio.async(hello_world())