@@ -158,6 +158,34 @@ This can also be achieved using the selectors_ module in Python 3.4:
158158 for event in device.read():
159159 print(event)
160160
161+
162+ Yet another possibility is asyncio in Python 3.4:
163+
164+ ::
165+
166+ import asyncio
167+ from evdev import list_devices, InputDevice, categorize
168+
169+ # Python 3.5 syntax, using "async for"
170+ async def dump_events(device):
171+ async for ev in device.read_loop():
172+ print(device.name, categorize(ev))
173+
174+ ## Python 3.4 syntax, using "yield from" in an infinite loop
175+ #@asyncio.coroutine
176+ #def dump_events(device):
177+ # while True:
178+ # evs = yield from device.async_read()
179+ # for ev in evs:
180+ # print(device.name, categorize(ev))
181+
182+ for file in list_devices():
183+ device = InputDevice(file)
184+ asyncio.ensure_future( dump_events( device ) )
185+
186+ asyncio.get_event_loop().run_forever()
187+
188+
161189
162190Accessing evdev constants
163191=========================
@@ -206,37 +234,27 @@ Reading events with asyncore
206234Reading events with asyncio
207235===========================
208236
209- An example program that prints the number of events by type every 5
210- seconds:
237+ To read a single event, you can use device.async_read_one()
211238
212239::
213240
214- import asyncio
241+ event = await dev.async_read_one()
242+
243+ To read a batch of events, you can use device.async_read():
244+
245+ ::
246+
247+ ev_batch = await dev.async_read()
248+ for ev in ev_batch:
249+ print(categorize(ev))
215250
216- from collections import Counter
217- from functools import partial
218- from evdev import InputDevice, ecodes
219-
220- mouse = InputDevice('/dev/input/event1')
221- keybd = InputDevice('/dev/input/event2')
222- counter = Counter()
223-
224- def read_events(device):
225- events = device.read()
226- counter.update([ev.type for ev in events])
227-
228- @asyncio.coroutine
229- def summarize():
230- while True:
231- yield from asyncio.sleep(5)
232- print('Number of events by type in the last 5 seconds:')
233- print({ecodes.EV[k]: v for k,v in counter.items()})
234- counter.clear()
235-
236- loop = asyncio.get_event_loop()
237- loop.add_reader(mouse, partial(read_events, mouse))
238- loop.add_reader(keybd, partial(read_events, keybd))
239- loop.run_until_complete(summarize())
251+ To read all events in an infinite loop, use dev.read_loop() and `async for `:
252+
253+ ::
254+ async for ev in dev.read_loop():
255+ print(categorize(ev))
256+
257+ See "Reading events from multiple devices" for a complete example using asyncio.
240258
241259
242260Getting exclusive access to a device
0 commit comments