Python" builtins.TypeError:必须是str,而不是字节" - Twisted LineReceiver.sendLine()

时间:2018-03-17 09:31:50

标签: python twisted

我正在关注Twisted教程(请参阅here的底部)

我正在尝试连接聊天服务器,但我不断收到以下错误

File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/internet/tcp.py", line 1073, in doRead
    protocol.makeConnection(transport)
  File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/internet/protocol.py", line 510, in makeConnection
    self.connectionMade()
  File "twisted_chat.py", line 12, in connectionMade
    self.sendLine("What's your name?") <------------- This line
  File "/Users/kevin/anaconda3/lib/python3.6/site-packages/twisted/protocols/basic.py", line 635, in sendLine
    return self.transport.write(line + self.delimiter)
builtins.TypeError: must be str, not bytes

似乎触发此错误的代码是

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    def __init__(self, users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?") <------- This line

    def connectionLost(self, reason):
        if self.name in self.users:
            del self.users[self.name]

我有点困惑,因为"What's your name?"显然是一个字符串,而不是字节。我正在使用Python 3.6和Twisted 17.9.0

编辑:我尝试在python 3.4中运行相同的代码,然后我得到了builtins.TypeError: Can't convert 'bytes' object to str implicitly

我一直在寻找,但似乎无法找到问题的解决方案。有谁知道我怎么解决这个问题?

1 个答案:

答案 0 :(得分:4)

除非你遗漏了一些代码,否则你的代码应该在Python / Anaconda v2中正常运行,但不能在v3中运行。对于Py v3 +,请使用:

self.sendLine( b"What's your name?" )

self.sendLine( "What's your name?".encode('utf8') )

正如您在LineReceiver.sendLine的文档中所看到的,参数必须是bytes类型。