2017-05-26 53 views
-1

下面的代码工作在Python 2得很好,但在python 3.6.1类型错误:对类字节对象是必需的,而不是“STR”错误在Python 2.7

model="XD4-170" 
ssh.send("more off\n") 
if ssh.recv_ready(): 
    output = ssh.recv(1000) 
ssh.send("show system-info\n") 
sleep(5) 
output = ssh.recv(5000) 
ll=output.split() # Python V3 

for item in ll: 
    if 'Model:' in item: 
    mm=item.split() 
    if mm[1]==model+',': 
     print("Test Case 1.1 - PASS - Model is an " + model) 
    else: 
     print("Test Case 1.1 - FAIL - Model is not an " + model) 

吐出以下错误错误输出:

if "Model:" in item: 
TypeError: a bytes-like object is required, not 'str' 

有一点指导将不胜感激。

+0

试试'if'Model:'in item.decode():' – RafaelC

+0

其实我需要将整个for循环转换为python 3 - 对于这个简单的代码片段的任何帮助将不胜感激。 @RafaelCardoso,你为什么要添加一个decode()? – pythonian

回答

1

Python 2.x和Python 3.x之间的主要区别之一是后者严格区分了strings and bytesrecv方法在一个插座(我假设这就是ssh是什么,因为你的代码不显示它被分配)返回一个bytes对象,而不是str。而且当你的对象,你得到listbytes,所以你的循环中的每个item也是一个bytes对象。

因此,当您的代码到达if 'Model:' in item:行时,它试图在bytes对象中找到str,这是无效的。

有两种方法可以解决这个问题:

  • 更改子到bytes对象:if b'Model:' in item:
  • 将从套接字读取的bytes解码为字符串:output = ssh.recv(5000).decode('UTF-8')
相关问题