another TypeError: a bytes-like object is required, not 'str'

another TypeError: a bytes-like object is required, not 'str'

我是 Python 的完全新手,但我从 1980 年左右开始就 (Liberty-)Basic 编程是为了好玩。

使用 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("on0xxx\n")
    output = session.read_some()
    while output:
        print (output)
        time.sleep(0.1)  # let the buffer fill up a bit
        output = session.read_some()

谁能告诉我为什么会出现 TypeError: a bytes-like object is required, not 'str' 以及如何解决它?

在Python3中(但不是在Python2中),str and bytes are distinct types不能混用。您不能将 str 直接写入套接字;你必须使用 bytes。只需在字符串文字前加上 b 即可使其成为 bytes 文字。

session.write(b"on0xxx\n")

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