Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeError:需要类似字节的对象,而不是';str';Python2.7中的错误_Python_Python 2.7_Python 3.x - Fatal编程技术网

TypeError:需要类似字节的对象,而不是';str';Python2.7中的错误

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

以下代码在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 '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()?