subprocess 和 Type Str 不支持缓冲区 API [英] subprocess and Type Str doesnt support the buffer API

查看:34
本文介绍了subprocess 和 Type Str 不支持缓冲区 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)对于 cmd.stdout 中的行:列 = line.split(' ')打印(列[3])

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

我在 Python 3.3 上做错了什么

解决方案

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

cmd = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE,universal_newlines=True)对于 cmd.stdout 中的行:列 = line.decode().split()如果列:打印(列[-1])

如果您使用 Python 3.6 或更新版本,您可以对 Popen() 调用使用显式 encoding 参数来指定要使用的不同编解码器,例如例如,UTF-8:

cmd = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE, encoding='utf8')对于 cmd.stdout 中的行:列 = line.split()如果列:打印(列[-1])

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

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

<预><代码>>>>b'one two'.split(' ')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>类型错误:类型 str 不支持缓冲区 API

通过解码,您可以避免该问题,并且您的 print() 调用也不必在输出前加上 b'..'.

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

导入操作系统对于 os.listdir('.') 中的文件名:打印(文件名)

I have

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

have error in line 3 Type Str doesnt support the buffer API.

What am i doing wrong i am on Python 3.3

解决方案

You are reading binary data, not str, so you need to decode the output first. If you set the universal_newlines argument to True, then stdout is automatically decoded using the result of the locale.getpreferredencoding() method (same as for opening text files):

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])

If you use Python 3.6 or newer, you can use an explicit encoding argument for to the Popen() call to specify a different codec to use, like, for example, 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])

If you need to use a different codec in Python 3.5 or earlier, don't use universal_newlines, just decode text from bytes explicitly.

You were trying to split a bytes value using a str argument:

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

By decoding you avoid that problem, and your print() call will not have to prepend the output with b'..' either.

However, you probably just want to use the os module instead to get filesystem information:

import os

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

这篇关于subprocess 和 Type Str 不支持缓冲区 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆