5 cases make Python output beautiful table!

来源 | Python数据之道

Foreword

Recently wrote a small tool with a python, this tool is mainly used to manage information resources, such as Ali cloud ECS and other information, because the computer using my work LINUX, so I thought to write a command line in Python management tool, the basic function is to synchronize information resources Ali cloud into the database, then you can use the command-line query.

Because the information is displayed in the command line, it all know, the command line to show the complexity of the text looks really tiring, so he can think of that show like form, it looks much more comfortable.

prettytable library is such a tool, prettytable can print out beautiful form, and Chinese support is quite good (if you have tried to achieve their own print form, you should know how much trouble dealing with the Chinese is)

Description: This article is written using Markdown syntax, in order to facilitate the display, as well as easy to copy, so this article does not use the screenshot, because the problem of format control, the results of the article will be some offset dividing line, showing in the terminal and this issue , please go to the manual operation verification.

installation

prettytable not a python's built-in library, through  pip install prettytableto installation.

A small example

Let's look at an example:

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable(['编号','云编号','名称','IP地址'])
table.add_row(['1','server01','服务器01','172.16.0.1'])
table.add_row(['2','server02','服务器02','172.16.0.2'])
table.add_row(['3','server03','服务器03','172.16.0.3'])
table.add_row(['4','server04','服务器04','172.16.0.4'])
table.add_row(['5','server05','服务器05','172.16.0.5'])
table.add_row(['6','server06','服务器06','172.16.0.6'])
table.add_row(['7','server07','服务器07','172.16.0.7'])
table.add_row(['8','server08','服务器08','172.16.0.8'])
table.add_row(['9','server09','服务器09','172.16.0.9'])
print(table)

Example above results are as follows:

linuxops@deepin:~$ python p.py 
+------+----------+----------+------------+
| 编号 |  云编号  |   名称   |   IP地址   |
+------+----------+----------+------------+
|  1   | server01 | 服务器01 | 172.16.0.1 |
|  2   | server02 | 服务器02 | 172.16.0.2 |
|  3   | server03 | 服务器03 | 172.16.0.3 |
|  4   | server04 | 服务器04 | 172.16.0.4 |
|  5   | server05 | 服务器05 | 172.16.0.5 |
|  6   | server06 | 服务器06 | 172.16.0.6 |
|  7   | server07 | 服务器07 | 172.16.0.7 |
|  8   | server08 | 服务器08 | 172.16.0.8 |
|  9   | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+

In the above example, we passed formimported form library. tableInstantiates a form library, and added ['编号','云编号','名称','IP地址']to the header, if the header is not added, it will be the default Field + number, for example:

+---------+----------+----------+------------+
| Field 1 | Field 2  | Field 3  |  Field 4   |
+---------+----------+----------+------------+

It is more intuitive to see the significance of each column, or to add header.

adding data

prettytable provides a way to add a variety of data, the most commonly used is the row should add the data columns.

A, add data row table.add_row

In the simple example above, we are adding rows of data.

If the data to be added in the form of a list, and the list and the length of the data length as the header. In actual use, we should pay attention to whether the added data and the corresponding header, which is very important.

B, according to add data columns table.add_column ()

See the following example:

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable()
table.add_column('项目', ['编号','云编号','名称','IP地址'])
table.add_column('值', ['1','server01','服务器01','172.16.0.1'])
print(table)

Results are as follows:

+-------+--------+------------+
| index | 项目 |    值     |
+-------+--------+------------+
|   1   |  编号  |     1      |
|   2   | 云编号 |  server01  |
|   3   |  名称  |  服务器01   |
|   4   | IP地址 | 172.16.0.1 |
+-------+--------+------------+

The example above, we by add_columnadding columns to the data in columns do not need to add data to develop header in the instance of the table when it is in the head of the table to add columns when specified.

table.add_column('项目', ['编号','云编号','名称','IP地址']) This line of code, for example, 项目specifies the header of this column called "project", ['编号','云编号','名称','IP地址']for the value of the column, the same as a list.

C, add data from csv file

PrettyTable not only provides a manually add data row by row, also supports reading data directly from a csv file.

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_csv 
reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable()
fp = open("res.csv", "r") 
table = from_csv(fp) 
print(table)
fp.close()

If you want to read the cvs file data, it must first import from_csvwill not operate. The above operation results of examples are as follows:

+------+----------+----------+------------+
| 编号 |  云编号  |   名称   |   IP地址   |
+------+----------+----------+------------+
|  1   | server01 | 服务器01 | 172.16.0.1 |
|  2   | server02 | 服务器02 | 172.16.0.2 |
|  3   | server03 | 服务器03 | 172.16.0.3 |
|  4   | server04 | 服务器04 | 172.16.0.4 |
|  5   | server05 | 服务器05 | 172.16.0.5 |
|  6   | server06 | 服务器06 | 172.16.0.6 |
|  7   | server07 | 服务器07 | 172.16.0.7 |
|  8   | server08 | 服务器08 | 172.16.0.8 |
|  9   | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+

xls csv file can not be obtained directly renaming, error. If the file is xls, csv file is available with the Save as csv

D, added value from sql query

Queries from the database data can be imported directly into the printed form, use the following example sqlite3, if you are using mysql is the same, as long as you can query the data into the table

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_db_cursor 
import sqlite3
reload(sys)
sys.setdefaultencoding('utf8')

conn = sqlite3.connect("/tmp/aliyun.db")
cur = conn.cursor()
cur.execute("SELECT * FROM res") 
table = from_db_cursor(cur)
print(table)

Results are as follows:

+------+----------+----------+------------+
| 编号 |  云编号  |   名称   |   IP地址   |
+------+----------+----------+------------+
|  1   | server01 | 服务器01 | 172.16.0.1 |
|  2   | server02 | 服务器02 | 172.16.0.2 |
|  3   | server03 | 服务器03 | 172.16.0.3 |
|  4   | server04 | 服务器04 | 172.16.0.4 |
|  5   | server05 | 服务器05 | 172.16.0.5 |
|  6   | server06 | 服务器06 | 172.16.0.6 |
|  7   | server07 | 服务器07 | 172.16.0.7 |
|  8   | server08 | 服务器08 | 172.16.0.8 |
|  9   | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+

E, import data from HTML

Support for importing from the table in html, the following example shows:

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_html 
reload(sys)
sys.setdefaultencoding('utf8')

html_string='''<table>
<tr>
<th>编号</th>
<th>云编号</th>
<th>名称</th>
<th>IP地址</th>
</tr>
<tr>
<td>1</td>
<td>server01</td>
<td>服务器01</td>
<td>172.16.0.1</td>
</tr>
<tr>
<td>2</td>
<td>server02</td>
<td>服务器02</td>
<td>172.16.0.2</td>
</tr>
</table>'''

table = from_html(html_string)

print(table[0])

Results are as follows:

+------+----------+----------+------------+
| 编号 |  云编号  |   名称   |   IP地址   |
+------+----------+----------+------------+
|  1   | server01 | 服务器01 | 172.16.0.1 |
|  2   | server02 | 服务器02 | 172.16.0.2 |
+------+----------+----------+------------+

As an example, we can import html form, but not the same place that printstatement, use html tables to import data when the print must be the first element in the list, or they may report []such errors.

This is because tablenot PrettyTable object, but the object contains a list of single PrettyTable it by parsing html from, so I can not print directly table, but you need to printtable[0]

Tabular output format

As support multiple input, the output table also supports multiple formats, we have used the print output way of example above, this is a common output.

A、print

Directly printprint out the form. In this way the form will be printed out with a border.

Form B, HTML output

print(table.get_html_string())You can print out the form html tag.

In the above example, a print(table.get_html_string())print out the following result:

<table>
    <tr>
        <th>编号</th>
        <th>云编号</th>
        <th>名称</th>
        <th>IP地址</th>
    </tr>
    <tr>
        <td>1</td>
        <td>server01</td>
        <td>服务器01</td>
        <td>172.16.0.1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>server02</td>
        <td>服务器02</td>
        <td>172.16.0.2</td>
    </tr>
</table>

Selective output

prettytable After creating a table, you can still have a choice of output certain line.

A, the output of the designated column

print table.get_string(fields=["编号", "IP地址"])You can specify the output column

B, both before output lines

By print(table.get_string(start = 0, end = 2))can print out the specified column, of course, startand endparameters so that I can freely control the display range. Of course, the interval contains startdoes not contain endis not very familiar with this usage?

According to the ranks of the specified output function, we can specify both rows and columns output here is not explained.

C, the table sliced

From the above output section, we make a bold assumption, since the interval contains startdoes not contain endas such rules and slices, we can not generate a new form by slicing and then print.

In fact it is possible.

new_table = table[0:2]
print(new_table)

In the code segment above, we can print a table of 2 rows 0-1 rows, Python slice extremely powerful, with slices we can freely enter any row.

D, output sequencing

Sometimes we need to sort the output table, use print table.get_string(sortby="编号", reversesort=True)can sort the table, which reversesortspecifies whether the reverse order, by default False, the default sequence being sorted.

sortbySpecifies a sort field.

Table style

A, built-in styles

By set_style()can set the table style, prettytable built a variety of styles personally feel MSWORD_FRIENDLY, PLAIN_COLUMNS, DEFAULT three style looks cool, look at this table from the display at a terminal on the tired, plus about fancy stuff looks even more tired .

In addition to the above recommended three styles, there is a style have to say that RANDOMthis is a random pattern, each print will be built in the style of a randomly selected, more fun.

Specifically built several styles, please refer to the official website to see the full output try it yourself.

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import MSWORD_FRIENDLY
from prettytable import PLAIN_COLUMNS
from prettytable import RANDOM
from prettytable import DEFAULT

reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable(['编号','云编号','名称','IP地址'])
table.add_row(['1','server01','服务器01','172.16.0.1'])
table.add_row(['3','server03','服务器03','172.16.0.3'])
table.add_row(['2','server02','服务器02','172.16.0.2'])
table.add_row(['9','server09','服务器09','172.16.0.9'])
table.add_row(['4','server04','服务器04','172.16.0.4'])
table.add_row(['5','server05','服务器05','172.16.0.5'])
table.add_row(['6','server06','服务器06','172.16.0.6'])
table.add_row(['8','server08','服务器08','172.16.0.8'])
table.add_row(['7','server07','服务器07','172.16.0.7'])
table.set_style(DEFAULT)

print(table)

B, starting from the style definitions

In addition to the built-in style, Prettytable also provides user-defined, e.g. alignment, digital output format, frame hyphens,

C, alignment settings

alignProvides the user set the alignment of the way, there is value l, r, cthe convenience of delegates left-aligned, right-aligned and centered If not set, the default center alignment.

D, control the border style

In PrettyTable, the frame consists of three parts, horizontal frame, a vertical frame, and a frame connector (horizontal, vertical, cross-linked symbols)

The following example:

#!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable

reload(sys)
sys.setdefaultencoding('utf8')

table = PrettyTable(['编号','云编号','名称','IP地址'])
table.add_row(['1','server01','服务器01','172.16.0.1'])
table.add_row(['3','server03','服务器03','172.16.0.3'])
table.add_row(['2','server02','服务器02','172.16.0.2'])
table.add_row(['9','server09','服务器09','172.16.0.9'])
table.add_row(['4','server04','服务器04','172.16.0.4'])
table.add_row(['5','server05','服务器05','172.16.0.5'])
table.add_row(['6','server06','服务器06','172.16.0.6'])
table.add_row(['8','server08','服务器08','172.16.0.8'])
table.add_row(['7','server07','服务器07','172.16.0.7'])
table.align[1] = 'l'

table.border = True
table.junction_char='$'
table.horizontal_char = '+'
table.vertical_char = '%'

print(table)
table.border`控制是否显示边框,默认是`True

table.junction_charBorder Control connector

table.horizontal_charSymbol cross-border control

table.vertical_charVertical frame control symbol

The embodiment operates as follows:

$++++++$++++++++++$++++++++++$++++++++++++$
% 编号 %  云编号  %   名称   %   IP地址   %
$++++++$++++++++++$++++++++++$++++++++++++$
%  1   % server01 % 服务器01 % 172.16.0.1 %
%  3   % server03 % 服务器03 % 172.16.0.3 %
%  2   % server02 % 服务器02 % 172.16.0.2 %
%  9   % server09 % 服务器09 % 172.16.0.9 %
%  4   % server04 % 服务器04 % 172.16.0.4 %
%  5   % server05 % 服务器05 % 172.16.0.5 %
%  6   % server06 % 服务器06 % 172.16.0.6 %
%  8   % server08 % 服务器08 % 172.16.0.8 %
%  7   % server07 % 服务器07 % 172.16.0.7 %
$++++++$++++++++++$++++++++++$++++++++++++$

More than a brief introduction to some common table style settings, please refer to the official website of concrete.

original:

https://linuxops.org/blog/python/prettytable.html

【end】

◆有奖征文◆


推荐阅读2020年,5种将死的编程语言检测、量化、追踪新冠病毒,基于深度学习的自动CT图像分析有多靠谱?GitHub 接连封杀开源项目惹众怒,CEO 亲自道歉!智能合约编写之 Solidity 的设计模式低学历、文科出身,我如何从月薪不到 3000 逆袭为大厂高薪程序员?从提取层、处理层、基础结构入手,带你了解Spark和Kafka!你点的每个“在看”,我都认真当成了AI
Released 1366 original articles · won praise 10000 + · views 6.43 million +

Guess you like

Origin blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/105020637