TypeError:需要类似字节的对象,而不是';str';Python2.7中的错误
以下代码在Python2中运行良好,但在Python3.6.1中出现了以下错误TypeError:需要类似字节的对象,而不是';str';Python2.7中的错误,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,以下代码在Python2中运行良好,但在Python3.6.1中出现了以下错误 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 'Mod
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'
非常感谢您提供一些指导。Python2.x和Python3.x之间的一个主要区别是后者严格区分了两者之间的区别。这个 方法返回一个
bytes
对象,而不是str
。当您split()
一个bytes
对象时,您会得到一个列表,其中包含字节
,因此循环中的每个项
也是一个字节
对象
因此,当代码到达item:
中的if'Model:行时,它试图在字节
对象中找到一个无效的str
有两种方法可以解决此问题:
- 将子字符串更改为
字节
对象:,如果项中有b'Model:
- 将从套接字读取的
字节解码为字符串:output=ssh.recv(5000)。解码('UTF-8')
在item.decode()中尝试if'Model::
实际上,我需要将整个for循环转换为python 3-对于此简单代码片段的任何帮助都将不胜感激@RafaelCardoso,你为什么要添加decode()?