python/cpython · error · RuntimeError

Cannot close a running event loop

Error message

Cannot close a running event loop

What it means

Error "Cannot close a running event loop" thrown in python/cpython.

Source

Thrown at Lib/asyncio/proactor_events.py:682

    def _make_duplex_pipe_transport(self, sock, protocol, waiter=None,
                                    extra=None):
        return _ProactorDuplexPipeTransport(self,
                                            sock, protocol, waiter, extra)

    def _make_read_pipe_transport(self, sock, protocol, waiter=None,
                                  extra=None):
        return _ProactorReadPipeTransport(self, sock, protocol, waiter, extra)

    def _make_write_pipe_transport(self, sock, protocol, waiter=None,
                                   extra=None):
        # We want connection_lost() to be called when other end closes
        return _ProactorWritePipeTransport(self,
                                           sock, protocol, waiter, extra)

    def close(self):
        if self.is_running():
            raise RuntimeError("Cannot close a running event loop")
        if self.is_closed():
            return

        if threading.current_thread() is threading.main_thread():
            signal.set_wakeup_fd(-1)
        # Call these methods before closing the event loop (before calling
        # BaseEventLoop.close), because they can schedule callbacks with
        # call_soon(), which is forbidden when the event loop is closed.
        self._stop_accept_futures()
        self._close_self_pipe()
        self._proactor.close()
        self._proactor = None
        self._selector = None

        # Close the event loop
        super().close()

    async def sock_recv(self, sock, n):

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Stop the proactor event loop (loop.stop()) and let run_forever() return before calling loop.close().
  2. Use asyncio.run() / asyncio.Runner to manage the loop lifecycle automatically.

When it happens

Trigger: Raised when loop.close() is called on a running proactor event loop.

Common situations: See trigger scenarios.


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/9a3562633fa77d11. Report an issue: GitHub.