Shravan J Kumar
Shravan J Kumar

Reputation: 158

Python: TypeError while searching in a string

When I run this code:

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

I get the following error:

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

I understand that this is to do with character encoding but I don't know where and how I need to convert this?

Upvotes: 1

Views: 79

Answers (3)

Anand S Kumar
Anand S Kumar

Reputation: 90889

For people who are wondering why this issue occured. From subprocess 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.

The default value for universal_newlines is False, which means that stdout is a binary stream, and the data it returns is a byte string.

And the issue occurs because we are trying to do a .find() on the byte string passing in string as argument. A very simple example to show this -

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

You should .decode() the data , Example -

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.

Upvotes: 1

Shravan J Kumar
Shravan J Kumar

Reputation: 158

stdout = Popen(callbackquery, shell=True, stdout=PIPE, universal_newlines=True).stdout
    output = stdout.read()

Upvotes: 0

galaxyan
galaxyan

Reputation: 6111

If  "No records were found that matched the search      criteria" in output:
  Do something 

Upvotes: 0

Related Questions