gpt4 book ai didi

Python:在字符串中搜索时出现类型错误

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

当我运行此代码时:

    stdout = Popen(callbackquery, shell=True, stdout=PIPE).stdout
output = stdout.read()
if output.find("No records were found that matched the search criteria") == -1:
print(output)
else:
# Do nothing
print("It's fine")

我收到以下错误:

   if output.find("No records were found that matched the search criteria") == -1:
TypeError: 'str' does not support the buffer interface

我知道这与字符编码有关,但我不知道需要在哪里以及如何转换它?

最佳答案

对于想知道为什么会出现此问题的人。来自子进程documentation -

If universal_newlines is True, the file objects stdin, stdout and stderr are opened as text streams in universal newlines mode, as described above in Frequently Used Arguments, otherwise they are opened as binary streams.

universal_newlines的默认值是False,这意味着stdout是一个二进制流,它返回的数据是一个字节字符串。

出现此问题是因为我们尝试对以 string 作为参数传递的字节字符串执行 .find() 。一个非常简单的例子来展示这一点 -

>>> b'Hello'.find('Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

您应该 .decode() 数据,示例 -

stdout = Popen(callbackquery, shell=True, stdout=PIPE, universal_newlines=True).stdout
output = stdout.read.decode('<encoding>') #The encoding with which the output of the other process is returned, can be something like utf-8, etc.

关于Python:在字符串中搜索时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31884839/

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