2017-04-17 101 views
-1

我在Python一个完整的新手,但我一直在从事编程的乐趣(自由─)基本距今约1980年另一类型错误:需要对类字节对象,而不是“STR”

使用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() 

谁能告诉我,为什么我得到的类型错误:一类字节对象是必需的,而不是“STR”,我该如何解决呢?

+0

可能重复的[TypeError:类似字节的对象是必需的,而不是'str'](http://stackoverflow.com/questions/33003498/typeerror-a-bytes-like-object-is-required-not -str) –

回答

0

在Python 3(但而不是Python 2中的),str and bytes are distinct types,不能混合。您不能直接将str写入套接字;你必须使用bytes。简单地用字符串前缀b作为bytes文字。

session.write(b"on0xxx\n") 
+0

这是我需要的,谢谢!我还必须在这里添加'b':session.write(b“on0xxx \ n”) – ON5MF

0

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

相关问题