user82048173
user82048173

Reputation: 5

Problems with "subprocess" module

I was trying to transform an output to a variable, I read online to use the subprocess module.

I tried this:

#coding: utf-8
import subprocess as sp
output = sp.check_output("echo test && pwd && ls", shell=True)
print(output)

But the output is:

# python test_subprocess.py
b'test\n/data/data/com.termux/files/home\nkali-armhf\nkalinethunter\ntest_subprocess.py\ntestip.py\nwebserver\n'

(Note: I use termux, a terminal emulator on Android)

How do I "convert" this output in a more clear one? Like with no b' or non working \n? Thanks

Upvotes: 0

Views: 341

Answers (4)

Sai Sri
Sai Sri

Reputation: 1

b' is something that is in bytes, so the output you got is also in bytes, you can decode it using decode() function and can use encode() to get back into bytes.

You can change print(output) to print(output.decode())

Upvotes: 0

MegaIng
MegaIng

Reputation: 7886

The sb.check_output function returns a bytes object, which is similar to a string but represents raw bytes. To actually see the decoded version of the raw data, use print(output.decode()) instead of just printing the output.

You see the current output, because the print function calls str on the bytes object, which falls back to a representation with as much information as possible. This means, that no automatic decoding will take place.

Upvotes: 3

jose_bacoy
jose_bacoy

Reputation: 12714

You can decode (translate byte to str) and replace new lines

print(output.decode('utf-8').replace('\\n', '\n')) 

Result:

test
/data/data/com.termux/files/home
kali-armhf
kalinethunter
test_subprocess.py
testip.py
webserver

Upvotes: 0

yaho cho
yaho cho

Reputation: 1779

Basically, I use it like this as below:

    data = subprocess.check_output(command, shell=True).decode('utf-8')
    data = data.replace('\\r\\n', '\n')

Upvotes: 0

Related Questions