Skip to content
Fix Code Error

Convert bytes to a string

March 13, 2021 by Code Error
Posted By: Tomas Sedovic

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 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

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() method is for, but when I tried it, I got the same byte array again:

>>> binascii.b2a_qp(command_stdout)
b'total 0n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2n'

How do I convert the bytes value back to string? I mean, using the “batteries” instead of doing it manually. And I’d like it to be OK with Python 3.

Solution

You need to decode the bytes object to produce a string:

>>> 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'
Answered By: zacherates

Related Articles

  • Running shell command and capturing the output
  • Pipe subprocess standard output to a variable
  • live output from subprocess command
  • How do I pass a string into subprocess.Popen (using the…
  • Capture the output of subprocess.run() but also print it in…
  • Fast way of finding lines in one file that are not in…
  • What's the difference between subprocess Popen and call (how…
  • Simplest way to create Unix-like continuous pipeline in…
  • read subprocess stdout line by line
  • How to execute a program or call a system command from…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I get PHP errors to display?

Next Post:

What does “Could not find or load main class” mean?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error