Python 2 到 3 的移植问题

1 投票
2 回答
577 浏览
提问于 2025-04-17 20:06

背景

我正在学习Python 3。为了快速入门,我把自己一个简单的Python 2脚本移植到Python 3。这个脚本非常简单,但我在一些问题上遇到了困难。

问题

  1. TypeError: 'str' does not support the buffer interface

我使用socket的.send()命令来发送服务器的欢迎信息。当服务器尝试发送这个信息时,我遇到了上面的错误。以下是相关的代码。

def clientthread(connection):

    #Sending message to connected client
    #This only takes strings (words

    connection.send("Welcome to the server. Type something and hit enter\n")

    #loop so that function does not terminate and the thread does not end
    while True:

        #Receiving from client
        data = connection.recv(1024)
        if not data:
            break
        connection.sendall(data)
        print (data)
    connection.close()

这是错误的详细信息:

Unhandled exception in thread started by <function clientthread at 0x1028abd40>
Traceback (most recent call last):
  File "/Users/*****/Desktop/Coding/Python 3/Sockets/IM Project/Server/Server v3.py", line 41, in clientthread
    connection.send("Welcome to the server. Type something and hit enter\n")
TypeError: 'str' does not support the buffer interface

备注:

我正在从Python 2.7.3移植到Python 3.3。

我会在遇到更多错误时继续添加。


编辑

虽然[这个]答案很好,但似乎还有一个问题——所有发送到服务器的消息前面都有一个b。我的客户端是用Python 2写的(我今晚会移植它)——这可能是问题的一部分吗?无论如何,以下是相关的代码。

客户端主循环

while True:   
    #Send some data to the remote server
    message = raw_input(">>>  ")

    try:
         #set the whole string
         s.sendall(USER + " :  " + message)
    except socket.error:
    #Send Failed
        print "Send failed"
        sys.exit()

    reply = s.recv(1024)
    print reply

Shell Stuff 服务器

HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx :  Hello'

2 个回答

0

在Python 3.*中,套接字(socket)发送和接收的数据都是字节(bytes)。所以你应该尝试这样做:

connection.send(b"Welcome to the server. Type something and hit enter\n")
1

你应该看看Python 3 的 Unicode 指南(还有将 Python 2 代码迁移到 Python 3 的指南)。send()这个函数需要的是字节数据,但你传给它的是字符串。在发送之前,你需要先调用字符串的encode()方法把它转换成字节数据,而在打印接收到的字节数据之前,你需要调用decode()方法把字节数据转换回字符串。

撰写回答