另一个类型错误:需要类似字节的对象,而不是"str"



我是Python中的一个完整新手,但是我从1980年开始就一直在为(Liberty-(基础编程。

使用Python 3.5.2我正在测试此脚本:

import time, telnetlib
host    = "dxc.ve7cc.net"
port    = 23
timeout = 9999
try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.read_until("login: ")
    session.write("on0xxxn")
    output = session.read_some()
    while output:
        print (output)
        time.sleep(0.1)  # let the buffer fill up a bit
        output = session.read_some()

谁能告诉我为什么我会得到 typeError:需要一个字节般的对象,而不是" str" 以及如何解决?

在python 3中(但是python 2中的不是(, strbytes是无法混合的不同类型。您不能将str直接写入插座;您必须使用bytes。只需将字符串字面的字面列表带有b即可使其成为bytes字面的文字。

session.write(b"on0xxxn")

与python 2.x不同,您不需要编码通过网络发送的数据,您必须在python 3.x中进行编码。因此,您想要发送的所有内容都需要使用.encode((函数编码。您收到的所有内容都需要用.decode((。

解码

最新更新