MCPcopy Create free account
hub / github.com/bslatkin/effectivepython / WriteThread

Class WriteThread

example_code/item_078.py:97–143  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

95from threading import Thread
96
97class WriteThread(Thread):
98 def __init__(self, output_path):
99 super().__init__()
100 self.output_path = output_path
101 self.output = None
102 self.loop = asyncio.new_event_loop()
103
104 def run(self):
105 asyncio.set_event_loop(self.loop)
106 with open(self.output_path, "wb") as self.output:
107 self.loop.run_forever()
108
109 # Run one final round of callbacks so the await on
110 # stop() in another event loop will be resolved.
111 self.loop.run_until_complete(asyncio.sleep(0))
112
113
114 print("Example 5")
115 async def real_write(self, data):
116 self.output.write(data)
117
118 async def write(self, data):
119 coro = self.real_write(data)
120 future = asyncio.run_coroutine_threadsafe(
121 coro, self.loop)
122 await asyncio.wrap_future(future)
123
124
125 print("Example 6")
126 async def real_stop(self):
127 self.loop.stop()
128
129 async def stop(self):
130 coro = self.real_stop()
131 future = asyncio.run_coroutine_threadsafe(
132 coro, self.loop)
133 await asyncio.wrap_future(future)
134
135
136 print("Example 7")
137 async def __aenter__(self):
138 loop = asyncio.get_event_loop()
139 await loop.run_in_executor(None, self.start)
140 return self
141
142 async def __aexit__(self, *_):
143 await self.stop()
144
145
146print("Example 8")

Callers 1

run_fully_asyncFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected