Hello i am using subprocess
.
import subprocess
proc = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
output = proc.stdout.read()
print(output)
output is correct
b'file.txt\nmain.py\nsource\ntest-page\n'
is there any way to beautify it , like in linux server ?
root@master:/home/python# ls
file.txt main.py source test-page
CodePudding user response:
You can use
print(output.decode().rstrip().replace("\n", " " * 2))
file.txt main.py source test-page
decode()
is to convert bytes to stringrstrip()
removes the last trailing"\n"
, but this is optionalreplace("\n", " " * 2))
will replace"\n"
(newline character) into 2 spaces
CodePudding user response:
Use split()
by newline to get the files, then print each on a separate line:
lines = output.split(b'\n')
for line in lines:
print(line.decode())
prints each file on a separate line:
file.txt
main.py
source
test-page
CodePudding user response:
Background on vertical format used by ls
Terminal uses space-separated columnar output, see GNU docs on ls
:
‘--format=vertical’
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 thedir
program. GNUls
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.
Simple
A simple two-spaces separation could be achieved by str.replace()
.
output = b'file.txt\nmain.py\nsource\ntest-page'
vertical = output.decode().replace('\n', ' ' * 2)
print(vertical)
Prints:
file.txt main.py source test-page
Columnar
Some advanced library can do the trick, e.g. columnar.