Search code examples
pythonsubprocesspopen

Why does Popen.communicate() return b'hi\n' instead of 'hi'?


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


Solution

  • 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