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

标签 python string python-3.x typeerror

当我运行此代码时:

    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/

相关文章:

python - Flask-RESTful-返回自定义响应格式

python-3.x - Pandas 从日期时间列中获取第二个最小值

python - 根据时间序列数据帧的时间列更正日期列中的条目

c - C 中的简单字符串加密

java - String#intern 关于实习生结果的困惑

python-3.x - 使用 setup.cfg 和通过 attr 访问的版本时出现 ModuleNotFoundError

python - 如何在 PyQt4 中保持按钮相对于标签大小的变化不变

python - 链接外部 C 库时来自 Cython 的 ImportError

Python动态多处理和信号问题

javascript - 使用未知长度字符串拆分 JavaScript 字符串,例如\n