0 votes
1 view
in Python by (47.8k points)

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

>>> from subprocess import * 

>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]

The communicate() method returns an array of bytes:

>>> 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'

However, I'd like to work with the output as a normal Python string. So that I could print it like this:

>>> 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

I thought that's what the binascii.b2a_qp() the method is for, but when I tried it, I got the same byte array again:

>>> 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'

Does anybody know how to convert the value of the byte back to a string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.

1 Answer

0 votes
by (107k points)

To convert python string to bytes you need to decode the bytes object to produce a string:-

>>> b"abcde" 

b'abcde' 

>>> b"abcde".decode("utf-8") 

'Abcde'

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.8k points)
+3 votes
2 answers
asked May 24, 2019 in Python by Krishna (2.6k points)
0 votes
1 answer
asked Nov 20, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...