Python 套接字:属性错误:__exit__ [英] Python Socket : AttributeError: __exit__

查看:57
本文介绍了Python 套接字:属性错误:__exit__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试运行以下示例:https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example在我的笔记本电脑中,但它不起作用.

服务器:

导入socketserver类 MyTCPHandler(socketserver.BaseRequestHandler):"""我们服务器的请求处理程序类.每次连接到服务器时,它都会被实例化一次,并且必须覆盖 handle() 方法以实现与客户."""定义句柄(自我):# self.request 是连接到客户端的 TCP 套接字self.data = self.request.recv(1024).strip()print("{} 写道:".format(self.client_address[0]))打印(self.data)# 只发回相同的数据,但大写self.request.sendall(self.data.upper())如果 __name__ == "__main__":主机, 端口 = "本地主机", 9999# 创建服务器,绑定到 localhost 的 9999 端口使用 socketserver.TCPServer((HOST, PORT), MyTCPHandler) 作为服务器:# 激活服务器;这将继续运行,直到你# 使用 Ctrl-C 中断程序server.serve_forever()

客户:

导入套接字导入系统主机, 端口 = "本地主机", 9999数据 = " ".join(sys.argv[1:])# 创建套接字(SOCK_STREAM 表示 TCP 套接字)使用 socket.socket(socket.AF_INET, socket.SOCK_STREAM) 作为袜子:# 连接服务器并发送数据袜子连接((主机,端口))sock.sendall(bytes(data + "\n", "utf-8"))# 从服务器接收数据并关闭收到 = str(sock.recv(1024), "utf-8")打印(发送:{}".格式(数据))打印(收到:{}".格式(收到))

此错误同时显示在客户端和服务器站点上:

回溯(最近一次调用最后一次):文件C:\Users\Win7_Lab\Desktop\testcl.py",第 8 行,在 <module> 中使用 socket.socket(socket.AF_INET, socket.SOCK_STREAM) 作为袜子:属性错误:__exit__[0.1s 内完成,退出代码为 1][shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\testcl.py"][目录:C:\Users\Win7_Lab\Desktop][路径:C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]

解决方案

看起来您尝试运行的示例是针对 Python 3 的,而您正在运行的版本是 Python 2.7.特别是,在 Python 3.2.

<块引用>

在 3.2 版更改:对上下文管理器协议的支持是添加.退出上下文管理器相当于调用 close().

如果您不想升级,您应该能够通过删除 with 语句并调用 close() 来修改您的代码,也许使用 try 语句:

尝试:server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)# 激活服务器;这将继续运行,直到你# 使用 Ctrl-C 中断程序server.serve_forever()除了:经过最后:server.close()

这个问题相关.>

I try to run example from : https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example in my laptop but it didn't work.

Server :

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()

Client :

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

This error is showing on both client and server site :

Traceback (most recent call last):
  File "C:\Users\Win7_Lab\Desktop\testcl.py", line 8, in <module>
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
AttributeError: __exit__
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\testcl.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]

解决方案

It looks like the example you're trying to run is for Python 3, while the version you're running is Python 2.7. In particular, support for using a context manager (i.e. with socket.socket()) was added in Python 3.2.

Changed in version 3.2: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling close().

If you don't want to upgrade, you should be able to modify your code by removing the with statements and calling close(), perhaps using a try statement:

try:
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
except:
    pass
finally:
    server.close()

Related to this question.

这篇关于Python 套接字:属性错误:__exit__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆