Skip to content

Commit 303ee65

Browse files
committed
cleanup asyncio_demo.py
1 parent 224c803 commit 303ee65

1 file changed

Lines changed: 24 additions & 10 deletions

File tree

examples/asyncio_demo.py

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
This example demonstrates how to use async IO with python-can.
5+
"""
6+
17
import asyncio
28
import can
39

@@ -8,7 +14,9 @@ def print_message(msg):
814

915

1016
async def main():
11-
can0 = can.Bus("vcan0", bustype="virtual", receive_own_messages=True)
17+
"""The main function that runs in the loop."""
18+
19+
bus = can.Bus("vcan0", bustype="virtual", receive_own_messages=True)
1220
reader = can.AsyncBufferedReader()
1321
logger = can.Logger("logfile.asc")
1422

@@ -19,9 +27,9 @@ async def main():
1927
]
2028
# Create Notifier with an explicit loop to use for scheduling of callbacks
2129
loop = asyncio.get_event_loop()
22-
notifier = can.Notifier(can0, listeners, loop=loop)
30+
notifier = can.Notifier(bus, listeners, loop=loop)
2331
# Start sending first message
24-
can0.send(can.Message(arbitration_id=0))
32+
bus.send(can.Message(arbitration_id=0))
2533

2634
print("Bouncing 10 messages...")
2735
for _ in range(10):
@@ -30,18 +38,24 @@ async def main():
3038
# Delay response
3139
await asyncio.sleep(0.5)
3240
msg.arbitration_id += 1
33-
can0.send(msg)
41+
bus.send(msg)
3442
# Wait for last message to arrive
3543
await reader.get_message()
3644
print("Done!")
3745

3846
# Clean-up
3947
notifier.stop()
40-
can0.shutdown()
48+
bus.shutdown()
49+
4150

51+
if __name__ == "__main":
52+
try:
53+
# Get the default event loop
54+
LOOP = asyncio.get_event_loop()
55+
# Run until main coroutine finishes
56+
LOOP.run_until_complete(main())
57+
finally:
58+
LOOP.close()
4259

43-
# Get the default event loop
44-
loop = asyncio.get_event_loop()
45-
# Run until main coroutine finishes
46-
loop.run_until_complete(main())
47-
loop.close()
60+
# or on Python 3.7+ simply
61+
#asyncio.run(main())

0 commit comments

Comments
 (0)