gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:12 24 4
gpt4 key购买 nike

我正在使用 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 对象。这意味着您还需要在针对这些对象的操作中使用字节对象。 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/55937881/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com