113

When trying to run the asyncio hello world code example given in the docs:

import asyncio

async def hello_world():
    print("Hello World!")

loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close()

I get the error:

RuntimeError: Event loop is closed

I am using python 3.5.3.

Roelant
  • 4,508
  • 1
  • 32
  • 62
TryingToTry
  • 1,033
  • 2
  • 9
  • 9
  • Does this answer your question? [Asyncio RuntimeError: Event Loop is Closed](https://stackoverflow.com/questions/32598231/asyncio-runtimeerror-event-loop-is-closed) – Arhadthedev Oct 26 '22 at 18:48

3 Answers3

171

On Windows seems to be a problem with EventLoopPolicy, use this snippet to work around it:

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
j4hangir
  • 2,532
  • 1
  • 13
  • 14
  • 15
    Thanks, but how did you even find this out? – Shryder Oct 06 '21 at 06:52
  • 5
    @Shryder Functional code started throwing this error after upgrading Python, I looked for what has changed between the python versions and saw the default EventLoopPolicy has been replaced (was mentioned somewhere in the docs). – j4hangir Nov 08 '21 at 00:21
  • 3
    If you use `asyncio.run` function, it will close the event loop – Ahmed Jun 07 '22 at 19:06
  • 1
    @j4hangir, sometimes you don't want to close the event loop and keep reusing it. I faced an error where I reuse the event loop and I had to revert to `asyncio.get_event_loop()` – Ahmed Jun 09 '22 at 18:18
  • 1
    Even using asyncio,run, I still had to set the loop policy to get it to work. Py3.10 – TASC Solutions Nov 02 '22 at 18:10
  • 1
    omg thanks, I've been trying to fix this error forever. Leaving a comment here in case anyone has same issue of getting this error when connecting to GCP Cloud SQL postgres via python and pg8000. Just import asyncio and put this line at the top. – weezilla Mar 16 '23 at 22:40
105

You have already called loop.close() before you ran that sample piece of code, on the global event loop:

>>> import asyncio
>>> asyncio.get_event_loop().close()
>>> asyncio.get_event_loop().is_closed()
True
>>> asyncio.get_event_loop().run_until_complete(asyncio.sleep(1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete
    self._check_closed()
  File "/.../lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

You need to create a new loop:

loop = asyncio.new_event_loop()

You can set that as the new global loop with:

asyncio.set_event_loop(asyncio.new_event_loop())

and then just use asyncio.get_event_loop() again.

Alternatively, just restart your Python interpreter, the first time you try to get the global event loop you get a fresh new one, unclosed.

As of Python 3.7, the process of creating, managing, then closing the loop (as well as a few other resources) is handled for you when use asyncio.run(). It should be used instead of loop.run_until_complete(), and there is no need any more to first get or set the loop.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 4
    If you still get `Event loop is closed` your code might be using a handle to the old event loop. – fuzzyTew Jan 06 '21 at 13:08
  • Any idea why it's still not working from this output and code? https://pastecode.io/s/894dr1o4 – Lod Aug 18 '23 at 15:21
  • 1
    @Lod it did work. The errors are exceptions in the event loop cleanup hooks. It does look messy and it’s caused by a [known aiohttp bug interacting with the Windows asyncio loop implementation](https://stackoverflow.com/questions/68123296/asyncio-throws-runtime-error-with-exception-ignored) but *your code* worked. That’s why the output starts with `3` before the `Exception ignored` part. – Martijn Pieters Aug 21 '23 at 08:27
26

...and just in case:

import platform
if platform.system()=='Windows':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

If you ever deploy your code in the cloud it might avoid painful debug.

skytaker
  • 4,159
  • 1
  • 21
  • 31
daviidarr
  • 261
  • 3
  • 3
  • windows event loop has very tight limitation on file descriptors number, https://stackoverflow.com/questions/47675410/python-asyncio-aiohttp-valueerror-too-many-file-descriptors-in-select-on-win – Gryu Feb 10 '22 at 12:37