Sto usando questo codice per ottenere lo standard output da un programma esterno:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Il metodo communicate() restituisce un array di byte:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Tuttavia, mi piacerebbe lavorare con l'output come una normale stringa Python. In modo da poterlo stampare in questo modo
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Pensavo che questo fosse ciò a cui serve il metodo binascii.b2a_qp(), ma quando l'ho provato, ho ottenuto di nuovo lo stesso array di byte:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Come posso riconvertire il valore del byte in stringa? Voglio dire, usando le "batterie" invece di farlo manualmente. E mi piacerebbe che andasse bene con Python 3.
È necessario decodificare l'oggetto byte per produrre una stringa:
>>> b"abcde"
b'abcde'
# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8")
'abcde'
È necessario decodificare la stringa di byte e trasformarla in una stringa di caratteri (Unicode).
Su Python 2
encoding = 'utf-8'
'hello'.decode(encoding)
o
unicode('hello', encoding)
Su Python 3
encoding = 'utf-8'
b'hello'.decode(encoding)
o
str(b'hello', encoding)
Credo che tu voglia davvero questo:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> command_text = command_stdout.decode(encoding='windows-1252')
La risposta di Aaron era corretta, tranne che devi sapere quale codifica usare. E credo che Windows usi 'windows-1252'. Avrà importanza solo se hai dei caratteri insoliti (non-ASCII) nel tuo contenuto, ma allora farà la differenza.
A proposito, il fatto che ha importanza è la ragione per cui Python è passato ad usare due tipi diversi per i dati binari e di testo: non può convertire magicamente tra loro, perché non conosce la codifica a meno che non gliela diciate voi! L'unico modo per saperlo è leggere la documentazione di Windows (o leggerla qui).