Fix Python – Why does Popen.communicate() return b’hi\n’ instead of ‘hi’?

Question

Asked By – imagineerThat

Can someone explain why the result I want, “hi”, is preceded with a letter ‘b’ and followed with a newline?

I am using Python 3.3

>>> import subprocess
>>> print(subprocess.Popen("echo hi", shell=True,
                           stdout=subprocess.PIPE).communicate()[0])
b'hi\n'

This extra ‘b’ does not appear if I run it with python 2.7

Now we will see solution for issue: Why does Popen.communicate() return b’hi\n’ instead of ‘hi’?


Answer

The echo command by default returns a newline character

Compare with this:

print(subprocess.Popen("echo -n hi", \
    shell=True, stdout=subprocess.PIPE).communicate()[0])

As for the b preceding the string it indicates that it is a byte sequence which is equivalent to a normal string in Python 2.6+

http://docs.python.org/3/reference/lexical_analysis.html#literals

This question is answered By – Necrolyte2

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0