[英]Python output beautifier subprocess
Hello i am using subprocess
.您好,我正在使用
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?有什么办法可以美化它,就像在 linux 服务器中一样?
root@master:/home/python# ls
file.txt main.py source test-page
Use split()
by newline to get the files, then print each on a separate line:使用
split()
by newline 获取文件,然后在单独的行上打印每个文件:
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
You can use您可以使用
print(output.decode().rstrip().replace("\n", " " * 2))
file.txt main.py source test-page
decode()
is to convert bytes to string decode()
是将字节转成字符串rstrip()
removes the last trailing "\n"
, but this is optional rstrip()
删除最后一个尾随的"\n"
,但这是可选的replace("\n", " " * 2))
will replace "\n"
(newline character) into 2 spaces replace("\n", " " * 2))
会将"\n"
(换行符)替换成2个空格ls
ls
使用的垂直格式的背景Terminal uses space-separated columnar output, see GNU docs on ls
:终端使用空格分隔的柱状输出,请参阅
ls
上的 GNU 文档:
'--format=vertical'
List files in columns, sorted vertically, with no other information.
在列中列出文件,垂直排序,没有其他信息。 This is the default for
ls
if standard output is a terminal.如果标准输出是终端,这是
ls
的默认值。 It is always the default for thedir
program.它始终是
dir
程序的默认值。 GNUls
uses variable width columns to display as many files as possible in the fewest lines.GNU
ls
使用可变宽度的列在最少的行中显示尽可能多的文件。
(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.
但它在列之间使用了 2 个空格。
A simple two-spaces separation could be achieved by str.replace()
.可以通过
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
Some advanced library can do the trick, eg columnar .一些高级库可以做到这一点,例如columnar 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.