【问题标题】:Python "builtins.TypeError: must be str, not bytes" - Twisted LineReceiver.sendLine()Python“builtins.TypeError:必须是str,而不是字节” - Twisted LineReceiver.sendLine()
【发布时间】:2018-03-17 09:31:50
【问题描述】:

我正在关注 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?" 显然是一个字符串,而不是字节。我正在使用带有 Twisted 17.9.0 的 Python 3.6

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

我一直在寻找,但似乎找不到问题的解决方案。有谁知道我该如何解决这个问题?

【问题讨论】:

  • 异常堆栈跟踪与您的代码不匹配。您确定您的代码触发了错误吗?
  • 如何查看?我所做的就是运行 twisted_chat.py 并尝试连接 nc 127.0.0.1 8123

标签: python twisted


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2018-09-13
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-19
    • 2020-11-22
    • 2016-06-25
    • 1970-01-01
    相关资源
    最近更新 更多