Gracefully Stopping an asyncio Server in Python 3.8
Автор: vlogommentary
Загружено: 2025-12-23
Просмотров: 1
Learn how to properly and cleanly stop an asyncio TCP server in Python 3.8 without runtime errors by using an asyncio.Event and controlled shutdown.
---
This video is based on the question https://stackoverflow.com/q/79473015/ asked by the user 'Ed Morton' ( https://stackoverflow.com/u/1745001/ ) and on the answer https://stackoverflow.com/a/79473198/ provided by the user 'James' ( https://stackoverflow.com/u/5003756/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.
Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: How to gracefully stop an asyncio server in python 3.8
Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.
If anything seems off to you, please feel free to drop me a comment under this video.
---
Introduction
When implementing TCP servers with Python's asyncio library (especially version 3.8), an important task is to stop the server gracefully when a certain condition is met—such as receiving a special quit command from a client. Simply calling loop.stop() inside a coroutine causes a RuntimeError because the event loop is stopped while unfinished tasks remain.
This guide explains how to properly signal and stop an asyncio server when a client sends the 'quit' command, avoiding such errors.
The Problem
If you call asyncio.get_event_loop().stop() directly within your async handler, the event loop stops immediately, potentially before the main asyncio.run() call completes. This results in:
[[See Video to Reveal this Text or Code Snippet]]
This means tasks (like your server or client handlers) are canceled abruptly without completing their cleanup.
Correct Approach: Using an asyncio.Event for Shutdown Coordination
Key idea:
Use an asyncio.Event to signal when the server should shut down.
Run the server's serve_forever() and wait for the shutdown event simultaneously.
Once the event is set (i.e., a quit message is received), gracefully close the server and let all tasks complete.
Benefits:
No abrupt loop stop.
Clean connections closed.
No runtime errors.
Improved Server Code Example
[[See Video to Reveal this Text or Code Snippet]]
Explanation:
The server runs serve_forever() alongside waiting for _shutdown_event.
When a client sends quit, the handler sets _shutdown_event.
The start() method detects the event and shuts down the server cleanly.
Client Code Adjustment
Make sure the client reads the server's final response after sending quit before closing:
[[See Video to Reveal this Text or Code Snippet]]
Summary
Avoid calling loop.stop() inside your async handlers.
Use an asyncio.Event to notify when to stop.
Use asyncio.wait() to run both server and shutdown event concurrently.
Close your server with server.close() and await server.wait_closed().
Handle client connections gracefully with proper reads and writes.
This approach ensures a smooth shutdown of your asyncio TCP server on receiving a "quit" command without raising runtime errors.
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: