From 2b33f5105336e149abb4f62c63e9381d48291389 Mon Sep 17 00:00:00 2001 From: Aleksander Wasaznik Date: Mon, 6 Feb 2017 20:22:01 +0100 Subject: [PATCH] Use asyncio.gather instead of asyncio.wait asyncio.gather immediatly propagates exceptions, which is nice for debugging, and what we wanted in the first place. --- grzegorz/__init__.py | 20 +++++++++++++------- grzegorz/nyasync.py | 26 +++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/grzegorz/__init__.py b/grzegorz/__init__.py index c2c0a7c..8274c54 100644 --- a/grzegorz/__init__.py +++ b/grzegorz/__init__.py @@ -1,15 +1,21 @@ import asyncio -from . import playlistmanage + +from . import mpv +from . import nyasync + +mpv_control = mpv.MPVControl() + +async def test(): + await mpv_control.send_request({"command":["loadfile",'grzegorz/res/logo.jpg']}) async def entry(): - await asyncio.wait([ - playlistmanage.metadatafetch_loop(), - ]) + await asyncio.gather( + mpv_control.run(), + test(), + ) def main(): - asyncio.get_event_loop().run_until_complete( - entry() - ) + nyasync.run(entry()) if __name__ == '__main__': main() diff --git a/grzegorz/nyasync.py b/grzegorz/nyasync.py index 516b496..9e6e74a 100644 --- a/grzegorz/nyasync.py +++ b/grzegorz/nyasync.py @@ -8,6 +8,21 @@ def ify(func): None, lambda: func(*args, **kwargs)) return asyncified +def safely(func, *args, **kwargs): + asyncloop = asyncio.get_event_loop() + asyncloop.call_soon_threadsafe(lambda: func(*args, **kwargs)) + +def callback(coro, callback=None): + asyncloop = asyncio.get_event_loop() + future = asyncio.run_cooroutine_threadsafe(coro, asyncloop) + if callback: + future.add_done_callback(callback) + return future + +def run(*coros): + asyncloop = asyncio.get_event_loop() + return asyncloop.run_until_complete(asyncio.gather(*coros)) + class Queue(asyncio.Queue): __anext__ = asyncio.Queue.get @@ -37,12 +52,17 @@ class Condition: with await self.monitor: self.monitor.notify_all() +async def unix_connection(path): + endpoints = await asyncio.open_unix_connection(path) + return UnixConnection(*endpoints) + class UnixConnection: - async def __init__(self, path): - (self.reader, self.writer) = await asyncio.open_unix_connection(path) + def __init__(self, reader, writer): + self.reader = reader + self.writer = writer def __aiter__(self): return self.reader.__aiter__() def write(self, data): - return self.writer.write(data); + self.writer.write(data)