subprocess和Type Str不支持缓冲区API

Nic*_*ach 20 python subprocess python-3.3

我有

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

在第3行中有错误类型Str不支持缓冲区API.

我在使用Python 3.3时做错了什么

Mar*_*ers 20

您正在读取二进制数据,str因此您需要先解码输出.如果将universal_newlines参数设置为True,则stdout使用locale.getpreferredencoding()方法的结果自动解码 (与打开文本文件相同):

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])
Run Code Online (Sandbox Code Playgroud)

如果使用Python 3.6或更高版本,则可以使用显式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])
Run Code Online (Sandbox Code Playgroud)

如果您需要在Python 3.5或更早版本中使用不同的编解码器,请不要使用universal_newlines,只需显式解码字节中的文本.

您试图bytes使用str参数拆分值:

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

通过解码,您可以避免这个问题,并且您的print()调用不必使用前置输出b'..'.

但是,您可能只想使用该os模块来获取文件系统信息:

import os

for filename in os.listdir('.'):
    print(filename)
Run Code Online (Sandbox Code Playgroud)