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

后端 未结 4 884

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



        
4条回答
  •  北海茫月
    2020-12-23 14:39

    As mentioned before, echo hi actually does return hi\n, which it is an expected behavior.

    But you probably want to just get the data in a "right" format and not deal with encoding. All you need to do is pass universal_newlines=True option to subprocess.Popen() like so:

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

    This way Popen() will replace these unwanted symbols by itself.

提交回复
热议问题