首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python 2-3移植问题

Python 2-3移植问题
EN

Stack Overflow用户
提问于 2013-03-24 02:32:58
回答 2查看 573关注 0票数 1

背景

我正在尝试学习Python 3。为了快速启动,我正在将我的一个简单的Python 2脚本移植到Python 3。这个脚本非常简单,我被困在了几个问题上。

The Issues

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

我使用socket .send()命令发送服务器的欢迎消息。当服务器试图发送它时,我会得到上面的错误。这是相关代码。

代码语言:javascript
复制
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()

这是回溯:

代码语言:javascript
复制
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

备注:

我正在从Python2.7.3移植到Python3.3

我会在错误出现的时候增加更多的错误。

编辑

尽管这是一个很好的答案,但似乎存在一个问题--所有发送到服务器的消息都在b之前。我的客户端在Python 2中(我今晚晚些时候会移植它)--这可能是问题的一部分吗?无论如何,这是相关的代码。

客户端主循环

代码语言:javascript
复制
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填充服务器

代码语言:javascript
复制
HOST: not_real.local
PORT: 2468
Socket Created
Socket Bind Complete
Socket now listening
Connected with 25.**.**.***:64203
b'xxmbabanexx :  Hello'
EN

回答 2

Stack Overflow用户

发布于 2013-03-24 02:39:22

您应该检查Python 3 Unicode指南 (以及将Python 2代码移植到Python 3)。send()需要字节,但是您要给它传递一个字符串。您需要在发送字符串之前调用字符串的encode()方法,并在打印它们之前调用接收到的字节的decode()方法。

票数 1
EN

Stack Overflow用户

发布于 2013-03-24 02:39:05

在python3.*中,套接字发送和接收的是字节。所以你应该试试:

代码语言:javascript
复制
connection.send(b"Welcome to the server. Type something and hit enter\n")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15594534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档