Convert bytes to a string

后端 未结 19 2867
野性不改
野性不改 2020-11-21 04:45

I\'m using this code to get standard output from an external program:

>>> from subprocess import *
>>> command_stdout = Popen([\'ls\', \'-l         


        
19条回答
  •  没有蜡笔的小新
    2020-11-21 04:54

    I think you actually want this:

    >>> from subprocess import *
    >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
    >>> command_text = command_stdout.decode(encoding='windows-1252')
    

    Aaron's answer was correct, except that you need to know which encoding to use. And I believe that Windows uses 'windows-1252'. It will only matter if you have some unusual (non-ASCII) characters in your content, but then it will make a difference.

    By the way, the fact that it does matter is the reason that Python moved to using two different types for binary and text data: it can't convert magically between them, because it doesn't know the encoding unless you tell it! The only way YOU would know is to read the Windows documentation (or read it here).

提交回复
热议问题