2013-04-04 30 views
20

我有子和類型海峽犯規支持緩衝API

cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) 
for line in cmd.stdout: 
    columns = line.split(' ') 
    print (columns[3]) 

在管線3類型海峽錯誤犯規支持緩衝API。

我在做什麼錯了,我是Python的3.3

回答

20

您正在閱讀的二進制數據,不str,所以你需要輸出第一解碼。

cmd = subprocess.Popen(
    'dir', shell=True, stdout=subprocess.PIPE, universal_newlines=True) 
for line in cmd.stdout: 
    columns = line.decode().split() 
    if columns: 
     print(columns[-1]) 

如果您使用Python 3.6或更新版本,你可以使用一個明確的:如果你的universal_newlines參數設置爲True,然後stdout自動使用的locale.getpreferredencoding() method 結果(相同打開文本文件)解碼encoding論據的Popen()調用指定不同的編解碼器的使用,等等,例如,UTF-8:

cmd = subprocess.Popen(
    'dir', shell=True, stdout=subprocess.PIPE, encoding='utf8') 
for line in cmd.stdout: 
    columns = line.split() 
    if columns: 
     print(columns[-1]) 

如果您需要在Python 3.5使用不同的編解碼器或更早版本,不使用universal_newlines ,十二月明確指定字節的文本。

你試圖使用str參數拆分bytes值:

>>> b'one two'.split(' ') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Type str doesn't support the buffer API 

通過解碼您避免這樣的問題,你的電話print()不會有b'..'預先設置輸出無論是。

然而,你可能只是想使用os模塊,而不是讓文件系統的信息:

import os 

for filename in os.listdir('.'): 
    print(filename) 
+0

感謝它作品,但任何想法,爲什麼我得到列表索引超出範圍錯誤 – 2013-04-04 17:23:56

+0

@NickLoach:行少於3列? – 2013-04-04 17:29:54

+0

Thanks Martijn the line has ['03 -04-2013','','19:48','','','','

','','','','','','' ','','','','','.ipython \ r \ n']我希望名爲.ipython的feild作爲輸出 – 2013-04-04 17:32:12

0

更好地利用binascii.b2a_uu二進制數據轉換成一行的ASCII字符

from binascii import b2a_uu 
cmd = b2a_uu(subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)) 
4

一個更簡單Martijn Pieters's answer的第一部分的解決方案是將universal_newlines=True參數傳遞給Popen調用。

我甚至會簡化這個到:

output = subprocess.check_output('dir', universal_newlines=True) 
columns = output.split() 
print(columns) 

注意:如果文件或目錄名稱包含空格,使用os.listdir('.')Martijn Pieters's answer或類似下面的內容提示:

output = subprocess.check_output('dir', universal_newlines=True) 
columns = [] 
for e in output.split(): 
    if len(columns) > 0 and columns[-1].endswith('\\'): 
     columns[-1] = columns[-1][:-1] + " " + e 
    else: 
     columns.append(e) 
print(columns) 
+0

'dir'是Windows上的內部命令,即如果沒有'dir.exe',那麼在這種情況下'shell = True'是必需的。 – jfs 2015-07-01 21:29:13

+0

@ J.F.Sebastian,感謝您指出這一點! – tjanez 2015-07-02 07:54:45

+0

如果我們假設一列輸出,那麼你可以使用'.splitlines()'來處理帶有空格的路徑 – jfs 2015-07-02 10:42:51

相關問題