Is there a tool in Python to create text tables like Powershell?
Whenever PowerShell displays its objects, it formats them in a nice pretty manner in the monospaced console, e.g.:
> ps
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
101 5 1284 3656 32 0.03 3876 alg
257 7 4856 10228 69 0.67 872 asghost
101 4 3080 4696 38 0.36 1744 atiptaxx
179 7 5568 7008 54 0.22 716 BTSTAC~1
...
Is there a similar library in Python or do I get to make 开发者_运维百科one?
I think python texttable module does exactly what you were looking for.
For further information.
pprint — Data pretty printer
There is a pprint
module which does a little bit of that. It's not as nice as your example but it does at least try to print 2-D and recursive data structures more intelligently than str()
.
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets, classes, or instances are included, as well as many other built-in objects which are not representable as Python constants.
numpy — Scientific computing
Then there is numpy
module which is targeted at mathematic and scientific computing, but is also pretty darn good at displaying matrices:
>>> from numpy import arange
>>> b = arange(12).reshape(4,3) # 2d array
>>> print b
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
I wrote this for my self; This is not exactly what is asked in the question, but it may help someone anyway :)
Usage:
table(
[
['Title A', 'Title B', 'Title C'],
['Value A', 'Value B', 'Value C'],
['101', '102', '103'],
['1000', '2000', '1234567890123456'],
['Text A', 'Text B', 'Text C']
]
)
I used rich for colors; but you can remove it.
Output:
Source code:
from rich import print
TBL_TOP = ['┌', '─', '┬', '┐']
TBL_MID = ['├', '─', '┼', '┤']
TBL_BTM = ['└', '─', '┴', '┘']
TBL_TXT = ['│', ' ', '│', '│']
TBL_TTL = ['╞', '═', '╪', '╡']
def word(word, size, color):
l = len(word)
if l > size:
return word[0:size] if l <= 3 else word[0:size-3]+'...'
space = size-l
return f'[{color}]'+word+(space*' ')+'[/]'
def draw(cols, w, num=' ', type=TBL_TOP, input=None, color='green'):
left, center, middle, right = type[:4]
print(f'{num} {left}', end='')
for col in range(0, cols):
print(center*w if type !=
TBL_TXT else word(input[col], w, color), end='')
print(middle, end='') if col < cols-1 else print(right)
def table(arr, w=15):
rows, cols = len(arr), len(arr[0])
draw(cols, w)
draw(cols, w, type=TBL_TXT, input=arr[0], color='yellow')
for r in range(1, rows):
draw(cols, w, type=TBL_TTL if r == 1 else TBL_MID)
draw(cols, w, type=TBL_TXT, num=r, input=arr[r])
if r == rows-1:
draw(cols, w, type=TBL_BTM)
pass
精彩评论