Python output beautifier subprocess

Hello i am using subprocess.

import subprocess

proc = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
output =

output is correct


is there any way  to beautify it , like in linux server ?

root@master:/home/python# ls
file.txt  source  test-page

Use split() by newline to get the files, then print each on a separate line:

lines = output.split(b'\n')

for line in lines:

prints each file on a separate line:


You can use

print(output.decode().rstrip().replace("\n", " " * 2))
file.txt   source   test-page
  • decode() is to convert bytes to string
  • rstrip() removes the last trailing "\n", but this is optional
  • replace("\n", " " * 2)) will replace "\n" (newline character) into 2 spaces

Background on vertical format used by ls

Terminal uses space-separated columnar output, see GNU docs on ls:


List files in columns, sorted vertically, with no other information. This is the default for ls if standard output is a terminal. It is always the default for the dir program. GNU ls uses variable width columns to display as many files as possible in the fewest lines.

(added emphasis in bold)

This means depending on the longest filename the column-width is adjusted and number of columns can vary. But it uses 2 spaces between the columns.


A simple two-spaces separation could be achieved by str.replace().

output = b'file.txt\\nsource\ntest-page'
vertical = output.decode().replace('\n', ' ' * 2)


file.txt  source  test-page


Some advanced library can do the trick, e.g. columnar.

Back to Top