The documentation for asyncio gives two examples for how to print "Hello World" every two seconds: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback https://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine
I can run those from the interpreter, but if I do I lose access to the interpreter. Can an asyncio event loop be run in the background, so that I can keep typing commands at the interpreter?
You can run the event loop inside a background thread:
Note that you must call
asyncio.set_event_loop
on theloop
, otherwise you'll get an error saying that the current thread doesn't have an event loop.If you want to interact with the event loop from the main thread, you'll need to stick to
loop.call_soon_threadsafe
calls.While this kind of thing is an ok way to experiment in the interpreter, in actual programs, you'll probably want all your code running inside the event loop, rather than introducing threads.