学习笔记之asyncio — Asynchronous I/O

asyncio — Asynchronous I/O — Python 3.8.5 documentation

A guide to using asyncio | Faculty

Service monitoring with python asyncio

Python async/await Tutorial

Hello World — Asyncio Documentation 0.0 documentation


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()
View Code

python - asyncio.run() cannot be called from a running event loop - Stack Overflow

posted on 2020-08-19 20:32  浩然119  阅读(418)  评论(0编辑  收藏  举报