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
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
您正在閱讀的二進制數據,不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)
更好地利用binascii.b2a_uu二進制數據轉換成一行的ASCII字符
from binascii import b2a_uu
cmd = b2a_uu(subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE))
一個更簡單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)
感謝它作品,但任何想法,爲什麼我得到列表索引超出範圍錯誤 – 2013-04-04 17:23:56
@NickLoach:行少於3列? – 2013-04-04 17:29:54
Thanks Martijn the line has ['03 -04-2013','','19:48','','','','