Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using split() with subprocess.check_output()

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.

like image 381
user138188 Avatar asked Dec 09 '22 08:12

user138188


1 Answers

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())
like image 184
jfs Avatar answered Dec 11 '22 09:12

jfs