I'm trying to take the output of upower -d (shell command) and split it into a long list using .split() so it can be searched.

When I do

import subprocess
dump = subprocess.check_output(["upower", "-d"])
print(dump.split())

it will print the output in list form as expected except every element in the list is preceded with a "b" (not inside the string).

When I do the same in python 2.7 it gives me the output I expect but I would like it to be in python 3.

  • Could you post the output in python3 and python2 ? – Roberto Mar 25 '14 at 7:46
up vote 4 down vote accepted

b"" is a bytes literal in Python. In Python 2.7, "" is also a bytestring. print(your_list) prints representations (repr) of each item that is why you see b"" in Python 3 but not in Python 2.

subprocess.check_output() returns bytes in both Python 2 and 3 unless universal_newlines=True specified in Python 3 that uses locale.getpreferredencoding(False) to decode the bytes.

from subprocess import check_output

output = check_output(["upower", "-d"], universal_newlines=True)
print(output.split())
  • +1 Better answer that mine. Thanks for your comments. – Roberto Mar 25 '14 at 9:38
  • Thanks for this, it solved the issue. Excuse the args not being in a list. I wrote the question at like 3 am. I was torn between putting "upower -d".split() and ["upower", "-d"]. – user138188 Mar 25 '14 at 12:40

You can also use dump.decode().split().

Decode will convert bytes into str, and then you can use split as before.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.