2017-05-26 77 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')
相關問題