user2105764
user2105764

Reputation: 25

Python 3.2 TypeError - can't figure out what it means

I originally put this code through Python 2.7 but needed to move to Python 3.x because of work. I've been trying to figure out how to get this code to work in Python 3.2, with no luck.

import subprocess
cmd = subprocess.Popen('net use', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
    if 'no' in line:
        print (line)

I get this error

if 'no' in (line):
TypeError: Type str doesn't support the buffer API

Can anyone provide me with an answer as to why this is and/or some documentation to read?

Much appreciated.

Upvotes: 1

Views: 428

Answers (1)

poke
poke

Reputation: 387647

Python 3 uses the bytes type in a lot places where the encoding is not clearly defined. The stdout of your subprocess is a file object working with bytes data. So, you cannot check if there is some string within a bytes object, e.g.:

>>> 'no' in b'some bytes string'
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    'no' in b'some bytes string'
TypeError: Type str doesn't support the buffer API

What you need to do instead is a test if the bytes string contains another bytes string:

>>> b'no' in b'some bytes string'
False

So, back to your problem, this should work:

if b'no' in line:
    print(line)

Upvotes: 1

Related Questions