You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行Python官方socketserver示例报错:AttributeError: __exit__

Fixing AttributeError: exit with Python socketserver TCPServer Example

Hey there! That AttributeError: __exit__ error you're hitting is super common when using older Python versions with the socketserver example from the docs. Let's break down what's going on and how to fix it:

Why This Happens

The official Python docs use a with statement to manage the TCPServer instance, like this:

with socketserver.TCPServer(("", 9999), MyTCPHandler) as server:
    server.serve_forever()

But here's the catch: TCPServer only gained support for the context manager protocol (which requires the __exit__ method) in Python 3.2. If you're running a version older than that, the interpreter won't recognize the with syntax for TCPServer, hence the AttributeError.

How to Fix It

You have two straightforward options:

Option 1: Upgrade Your Python Version

If possible, upgrade to Python 3.2 or newer. This lets you use the exact example from the docs without any changes. You can check your current version by running:

python --version

Option 2: Manually Manage Server Lifecycle (No with Statement)

If upgrading isn't an option, replace the with block with explicit try/finally to handle server cleanup:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    本服务器的请求处理类,每次与服务器建立连接时实例化一次,必须重写handle()方法以实现与客户端的通信。
    """
    def handle(self):
        # 补全你的handle逻辑,这里用官方示例的基础通信代码做参考
        self.data = self.request.recv(1024).strip()
        print(f"收到来自 {self.client_address[0]} 的数据: {self.data!r}")
        self.request.sendall(self.data.upper())

# 不用with语句初始化服务器
server = socketserver.TCPServer(("", 9999), MyTCPHandler)
try:
    print("服务器在9999端口运行中...")
    server.serve_forever()
finally:
    # 确保服务器停止时正确清理资源
    server.server_close()

This does the same job as the with statement—making sure the server closes correctly—but works on older Python versions.

Quick Check

Double-check that your original code was using the with syntax to wrap the TCPServer instance. That's almost certainly where the error is coming from, since your handler class code (even the cut-off part) doesn't relate to the __exit__ method.

内容的提问来源于stack exchange,提问作者Park Yo Jin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:59:51