Python源码示例:asyncio.async()
示例1
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
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
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
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
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
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
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
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
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
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
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
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
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
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
def hello_world():
yield from asyncio.sleep(1)
print('Hello World')
asyncio.async(hello_world())
示例16
def good_evening():
yield from asyncio.sleep(1)
print('Good Evening')
asyncio.async(good_evening())
示例17
def __init__(self, cb):
super().__init__()
self.cb = cb
self.cnt= 0
self.log = logging.getLogger() #.getChild('TcpConnection')
self.log.info('TcpConnection: creating TcpCOnnection')
self.queue = asyncio.Queue(maxsize=100)
self.hipri_queue = asyncio.Queue()
self._ready = asyncio.Event()
self._msg_ready = asyncio.Semaphore(value=0)
self.tsk= asyncio.async(self._send_messages()) # Or asyncio.ensure_future if using 3.4.3+
self.flush= False
示例18
def _write(self, data):
# calls the send_message in Serial Connection proto which is a queue
#self.log.debug('CommsNet: _write ' + data)
if self.proto:
asyncio.async(self.proto.send_message(data))
示例19
def _get_reports(self):
# calls the send_message in Serial Connection proto which is a queue
if self.proto:
asyncio.async(self.proto.send_message('M105\n', True))
asyncio.async(self.proto.send_message('?', True))
self.timer = async_main_loop.call_later(5, self._get_reports)
示例20
def _stream_file(self, fn):
self.file_streamer= asyncio.async(self.stream_file(fn))
示例21
def run(self):
self._runner = asyncio.async(self._run(), loop=self.loop)
try:
self.loop.run_until_complete(self._runner)
finally:
self.loop.close()
示例22
def hangups_start(self):
"""Connect to Hangouts"""
cookies = self.login(self.refresh_token_path)
if cookies:
self.startHangups.emit()
self.client = hangups.Client(cookies)
self.client.on_connect.add_observer(self.on_connect)
# Run Hangups event loop
asyncio.async(
self.client.connect()
).add_done_callback(lambda future: future.result())
self.hangups_running = True
self.update_status()
示例23
def hangups_stop(self):
"""Disconnect from Hangouts"""
self.stopHangups.emit()
asyncio.async(
self.client.disconnect()
).add_done_callback(lambda future: future.result())
self.conv_list = None
self.user_list = None
self.notifier = None
self.hangups_running = False
self.client = None
self.update_status()
示例24
def on_scroll_requested(self, dx, dy, rect_to_scroll):
"""User has scrolled in messagesWebView (callback)"""
frame = self.messagesWebView.page().mainFrame()
if frame.scrollPosition().y() == frame.scrollBarMinimum(QtCore.Qt.Vertical):
future = asyncio.async(self.load_events())
future.add_done_callback(lambda future: future.result())
示例25
def execute(self, loop):
self._loop = loop
res = self.reload()
if not res: return
asyncio.Task(self._update())
while 1:
logger.debug('새로운 업데이트가 뜨기를 기다리고 있습니다.')
update = yield from self.queue.get()
asyncio.async(self._process(update))
示例26
def _execute_plugin(self, plugin_name, params, account, history):
if plugin_name not in self.plugins:
logger.warning('"{}" 플러그인은 로드되지 않은 플러그인입니다.'.format(plugin_name))
return
plugin = self.plugins[plugin_name]
worker = asyncio.async(plugin.execute(account=account, history=history,
params=params))
if plugin.wait:
yield from asyncio.wait([worker])
示例27
def _start_profiling(self):
asyncio.async(self.profile_periodically())
示例28
def _start_watching(self, client):
reader, writer = client
disconnected = lambda x: self.disconnected(reader, writer)
asyncio.async(reader.read()).add_done_callback(disconnected)
示例29
def add_task(self, task):
"""
Some Task objects are associated with the peer. This method
gives an easy way to keep a strong reference to a Task that won't
disappear until the peer does.
"""
self._tasks.add(asyncio.async(task))
示例30
def on_next(self, msg):
# send message on tcp stream
print("tcp: on_next")
for task, (reader, writer) in self.clients.items():
try:
print("tcp: writing to client")
writer.write(str(msg).encode('utf-8'))
writer.write('\n'.encode('utf-8'))
asyncio.async(writer.drain()) # can this raise exception?
except ConnectionResetError:
print("tcp: client disconnected")
del self.clients[task]
print("tcp: on_next done")