学习笔记之asyncio — Asynchronous I/O
asyncio — Asynchronous I/O — Python 3.8.5 documentation
- https://docs.python.org/3/library/asyncio.html?highlight=asyncio
- asyncio is a library to write concurrent code using the async/await syntax.
- Coroutines and Tasks — Python 3.8.5 documentation
- Event Loop — Python 3.8.5 documentation
- https://docs.python.org/3/library/asyncio-eventloop.html
- asyncio.get_event_loop()
- https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_event_loop
- Get the current event loop.
- loop.run_until_complete(future)
- https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_until_complete
- Run until the future (an instance of
Future
) has completed.
- loop.run_forever()
- https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_forever
- Run the event loop until
stop()
is called.
A guide to using asyncio | Faculty
- https://faculty.ai/blog/a-guide-to-using-asyncio/
- https://github.com/acroz/asyncio-example
- https://github.com/acroz/asyncio-example/blob/master/agent.py
Service monitoring with python asyncio
Python async/await Tutorial
Hello World — Asyncio Documentation 0.0 documentation
- https://asyncio.readthedocs.io/en/latest/hello_world.html
- This is a series of examples showing the basics of how to write coroutines and schedule them in the asyncio event loop.
How to start / stop / run a service ?
1 import asyncio 2 import logging 3 import zmq 4 import zmq.asyncio 5 6 7 class TestService: 8 9 def __init__(self, url): 10 self._url = url 11 12 self._is_running = False 13 self._zmq_context = None 14 self._socket = None 15 16 def _start(self): 17 if self._is_running: 18 return 19 20 self._zmq_context = zmq.asyncio.Context() 21 self._socket = self._zmq_context.socket(zmq.REP) 22 self._socket.bind(self._url) 23 24 def _stop(self): 25 if not self._is_running: 26 return 27 28 if not self._socket.closed: 29 self._socket.close() 30 31 async def _process_message(self, data): 32 # Process message here 33 return data 34 35 async def _recv_and_process(self): 36 # need while loop to keep receiving and processing messages 37 while (True): 38 msg = await self._socket.recv_multipart() 39 reply = await self._process_message(msg) 40 await self._socket.send_multipart([reply,]) 41 42 def run(self): 43 loop = None 44 45 try: 46 self._start() 47 48 loop = asyncio.get_event_loop() 49 loop.create_task(self._recv_and_process()) 50 loop.run_forever() 51 52 except Exception as ex: 53 logging.error('Error {}'.format(ex)) 54 55 finally: 56 if loop is not None: 57 loop.close() 58 59 self._stop()
python - asyncio.run() cannot be called from a running event loop - Stack Overflow