11Tutorial
22--------
33
4+
45Listing accessible event devices
56================================
67
@@ -158,33 +159,49 @@ This can also be achieved using the selectors_ module in Python 3.4:
158159 for event in device.read():
159160 print(event)
160161
161-
162- Yet another possibility is asyncio in Python 3.4:
162+
163+ Yet another possibility is the :mod: ` asyncio ` module from Python 3.4:
163164
164165::
165166
166- import asyncio
167- from evdev import list_devices, InputDevice, categorize
167+ import asyncio, evdev
168+
169+ @asyncio.coroutine
170+ def print_events(device):
171+ while True:
172+ events = yield from device.async_read()
173+ for event in events:
174+ print(device.fn, evdev.categorize(event), sep=': ')
175+
176+ mouse = evdev.InputDevice('/dev/input/eventX')
177+ keybd = evdev.InputDevice('/dev/input/eventY')
178+
179+ for device in mouse, keybd:
180+ asyncio.async(print_events(device))
168181
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))
182+ loop = asyncio.get_event_loop()
183+ loop.run_forever()
173184
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))
185+ Since Python 3.5, the `async/await
186+ <https://docs.python.org/3/library/asyncio-task.html> `_ syntax makes this
187+ even simpler:
181188
182- for file in list_devices():
183- device = InputDevice(file)
184- asyncio.ensure_future( dump_events( device ) )
189+ ::
190+
191+ import asyncio, evdev
192+
193+ mouse = evdev.InputDevice('/dev/input/event4')
194+ keybd = evdev.InputDevice('/dev/input/event5')
185195
186- asyncio.get_event_loop().run_forever()
196+ async def print_events(device):
197+ async for event in device.read_iter():
198+ print(device.fn, evdev.categorize(event), sep=': ')
187199
200+ for device in mouse, keybd:
201+ asyncio.ensure_future(print_events(device))
202+
203+ loop = asyncio.get_event_loop()
204+ loop.run_forever()
188205
189206
190207Accessing evdev constants
@@ -238,7 +255,7 @@ To read a single event, you can use device.async_read_one()
238255
239256::
240257
241- event = await dev.async_read_one()
258+ event = await dev.async_read_one()
242259
243260To read a batch of events, you can use device.async_read():
244261
@@ -253,7 +270,7 @@ To read all events in an infinite loop, use dev.read_loop() and `async for`:
253270::
254271 async for ev in dev.read_loop():
255272 print(categorize(ev))
256-
273+
257274See "Reading events from multiple devices" for a complete example using asyncio.
258275
259276
0 commit comments