Find substring in Popen stdout raises "TypeError: a bytes-like object is required, not str" after updating from Python 2 to 3

Question:

I am updating a program from Python 2 to Python 3.

The program checks a lot if a string is found within stdout of a command, however in Python 3, I am getting lots of issues with this.

cmd = 'ps aux | grep iproxy'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
        
if 'iproxy 2222 22' in stdout:
File "/Users/ben/Documents/ios/iosation/iosation3.py", line 469, in startConf
if 'iproxy 2222 22' in stdout:
TypeError: a bytes-like object is required, not 'str

Changing it to a proper string find method basically gives me the same error.

str2 = 'iproxy 2222 22'
if stdout.find(str2):
if stdout.find(str2):
TypeError: argument should be integer or bytes-like object, not 'str'

Worked fine for years under Python 2, but Python 3 doesn’t like it, how come?

Asked By: jerrythebum

||

Answers:

The issue you’re facing is due to a difference in how strings are handled in Python 2 and Python 3. In Python 2, the default string type is ASCII, which is compatible with the bytes type. However, in Python 3, the default string type is Unicode, which is not compatible with the bytes type.

I think this would work.

cmd = 'ps aux | grep iproxy'
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
        
if b'iproxy 2222 22' in stdout.decode('utf-8'):
    # Do something
Answered By: Vipul Ram
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.