python - 子进程 "TypeError: a bytes-like object is required, not ' str'"

标签 python string subprocess

我正在使用来自 a previously asked question a few years ago 的代码但是,我认为这已经过时了。尝试运行代码时,我收到了上面的错误。我仍然是 Python 的新手,所以我无法从类似的问题中得到太多的澄清。有谁知道为什么会这样?

import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

print(getLength('bell.mp4'))

回溯

Traceback (most recent call last):
  File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
    print(getLength('bell.mp4'))
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
    return [x for x in result.stdout.readlines() if "Duration" in x]
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
    return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a bytes-like object is required, not 'str'

最佳答案

subprocess 默认为 stdout 或 stderr 流返回 bytes 对象。这意味着您还需要在针对这些对象的操作中使用 bytes 对象。 x 中的“Duration” 使用 str 对象。使用字节文字(注意 b 前缀):

return [x for x in result.stdout.readlines() if b"Duration" in x]

或者如果您知道使用的编码(通常是语言环境默认值,但您可以 set LC_ALL or more specific locale environment variables 用于子进程),则首先解码您的数据:

return [x for x in result.stdout.read().decode(encoding).splitlines(True)
        if "Duration" in x]

另一种方法是通过将 encoding 参数设置为合适的编解码器来告诉 subprocess.Popen() 将数据解码为 Unicode 字符串:

result = subprocess.Popen(
    ["ffprobe", filename],
    stdout=subprocess.PIPE, stderr = subprocess.STDOUT,
    encoding='utf8'
)

如果您设置text=True(Python 3.7 及更高版本,在以前的版本中,此版本称为universal_newlines)您还可以启用解码,使用您的system default codec ,与用于 open() 调用的相同。在这种模式下,管道默认是行缓冲的。

关于python - 子进程 "TypeError: a bytes-like object is required, not ' str'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989808/

相关文章:

regex - 从字符串中提取版本号,最佳方法?

javascript - 我应该如何从 Java 应用程序运行 NodeJS?

python - 在python脚本中调用bash配置文件来设置环境变量

python - 需要帮助从纪元时间中剥离微秒

python - 如何计算数据框的百分比

python - 更新多对多关系

python - 从 python 中的类似 cron 的调度程序中删除事件

python文件读取

java - 如何更改所有应用程序中android字符串的名称

python - subprocess.Popen 进程标准输出返回空?