2013-02-25 77 views
1

我原本是通過Python 2.7放入這段代碼,但因爲工作需要移植到Python 3.x。我一直在試圖弄清楚如何讓這個代碼在Python 3.2中工作,沒有運氣。Python 3.2 TypeError - 無法弄清楚它是什麼意思

import subprocess 
cmd = subprocess.Popen('net use', shell=True, stdout=subprocess.PIPE) 
for line in cmd.stdout: 
    if 'no' in line: 
     print (line) 

我得到這個錯誤

if 'no' in (line): 
TypeError: Type str doesn't support the buffer API 

誰能給我一個答案,爲什麼這是和/或一些文檔閱讀?

非常感謝。

回答

1

Python 3在很多編碼沒有明確定義的地方使用bytes類型。子進程的stdout是一個使用字節數據的文件對象。如果這些字節字符串包含另一個字節

>>> 'no' in b'some bytes string' 
Traceback (most recent call last): 
    File "<pyshell#13>", line 1, in <module> 
    'no' in b'some bytes string' 
TypeError: Type str doesn't support the buffer API 

你需要做的,而不是什麼是測試:

>>> b'no' in b'some bytes string' 
False 
所以,你不能檢查,如果有一個字節對象中一些字符串,如

所以,回到你的問題,這應該工作:

if b'no' in line: 
    print(line) 
+0

非常有趣,非常感謝。現在可以多讀一點字節了。 – user2105764 2013-02-26 03:11:42

相關問題