Three stop(); run_forever() stop(); run_forever() works due to the implementation of stop :
def stop(self): """Stop running the event loop. Every callback scheduled before stop() is called will run. Callback scheduled after stop() is called won't. However, those callbacks will run if run() is called again later. """ self.call_soon(_raise_stop_error) def _raise_stop_error(*args): raise _StopError
So, the next time the event loop _raise_stop_error and executes pending callbacks, it will raise _raise_stop_error , which raises _StopError . The run_forever will only break into this particular exception:
def run_forever(self): """Run until stop() is called.""" if self._running: raise RuntimeError('Event loop is running.') self._running = True try: while True: try: self._run_once() except _StopError: break finally: self._running = False
So, by planning a stop() and then calling run_forever , you start one iteration of the event loop and then stop as soon as it accesses the _raise_stop_error return message. You may also have noticed that _run_once is defined and run_forever is run_forever . You can call it directly, but sometimes it can block if there are no callbacks ready to run, which may be undesirable. I donβt think there is a cleaner way to do it now - this answer was provided by Andrei Svetlov, who is a contributor to asyncio ; he would probably know if there is a better option. :)
All in all, your code looks reasonable, although I think you should not use this run_once approach to start. It is not deterministic; if you had a longer list or a slower system, printing it all might require more than two additional iterations. Instead, you should just send a watchdog that tells the receiver to complete the work, and then wait for the send and receive commands to complete:
import sys import time import socket import asyncio addr = ('127.0.0.1', 1064) SENTINEL = b"_DONE_"
Finally, asyncio.async is the right way to add tasks to the event loop. create_task was added in Python 3.4.2, so if you have an earlier version, it will not exist.