Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to output beautiful tables

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use Python to output beautiful tables". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Preface

Recently, I am using python to write a gadget, this tool is mainly used to manage the information of various resources, such as Ali Yun's ECS and other information, because the computer I work on uses LINUX, so I want to write a command line management tool with Python. The basic function is to synchronize the information of Ali Yun's resources to the database, and then you can use the command line to query.

Because the information is displayed on the command line, it is well known that displaying complex text on the command line looks really tiring, so thinking that it can be displayed like a table, it looks much more comfortable.

The prettytable library is such a tool. Prettytable can print beautiful forms and supports Chinese quite well (if you are trying to implement your own printing forms, you should know how troublesome it is to deal with Chinese).

two。 Installation

Prettytable is not a built-in library for python and can be installed through pip install prettytable.

3. A small example

Let's first look at an example:

#! / usr/bin/python # * * coding:utf-8** import sys from prettytable import PrettyTable reload (sys) sys.setdefaultencoding ('utf8') table = PrettyTable ([' serial number', 'cloud number', 'name','IP address']) table.add_row (['1Med' server01 'server' server '01'' server '172.16.0.1']) table.add_row ([' 2' 'server02' 'server' server'' '172.16.0.2']) table.add_row ([' 3pl server03paramagement]) table.add_row (['4pl' server04' 'server04'' server '172.16.0.4']) table.add_row (['5pl' server05' 'server05') table.add_row ([' 6pl 'server06') ]) table.add_row (['7mecomy' server07'']) table.add_row (['8pl' server08' 'server' 172.16.0.8']) table.add_row (['9zhuo' server09' 'server' 09'']) print (table)

The running result of the above example is as follows:

Linuxops@deepin:~$ python p.py +-+ | number | Cloud ID | name | IP address | +-+ | 1 | | server01 | Server 01 | 172.16.0.1 | | 2 | server02 | Server 02 | 172.16.0.2 | | 3 | server03 | Server 03 | 172.16.0.3 | | 4 | server04 | Server 04 | 172.16.0.4 | | 5 | server05 | Server 05 | 172.16.0.5 | | 6 | server06 | Server 06 | 172.16.0.6 | | 7 | server07 | Server | 07 | 172.16.0.7 | | 8 | server08 | Server 08 | 172.16.0.8 | | 9 | server09 | Server 09 | 172.16.0.9 | +-+

In the above example, we imported the table library through form. Table instantiates a table library and adds ['number', 'cloud number', 'name','IP address'] as the header. If no header is added, it will be displayed with the default Field+ number, for example:

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

So in order to see the meaning of each column more intuitively, add a header.

4. Add data

Prettytable provides a variety of ways to add data, the most common of which is to add data by row by column.

A. Add data table.add_row by row

In the simple example above, we add data by row.

The added data must be in the form of a list, and the list length of the data must be the same as the length of the header. In practical use, it is important to pay attention to whether the added data corresponds to the header.

B. Add data table.add_column by column ()

Look at 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 (' project', ['serial number', 'cloud number', 'name','IP address']) table.add_column ('value', ['1ZJI' 'server01'' server 01' MJ172.16.0.1']) print (table)

The running results are as follows:

+-+ | index | Project | value | +-+ | 1 | number | 1 | | 2 | Cloud number | server01 | | 3 | name | Server 01 | 4 | IP address | 172.16.0.1 | +-+

In the above example, we use add_column to add data by column. Adding data by column does not require a header when the table is instantiated, its header is specified when the column is added.

Table.add_column ('project', ['number', 'cloud number', 'name','IP address']) as an example, the project specifies that the header of this column is "project", ['number', 'cloud number', 'name','IP address'] as the value of the column, which is also a list.

C, add data from csv file

PrettyTable not only provides manual addition of data by row and column, but also supports reading data directly from csv files.

#! / 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 cvs file data, you must import from_csv first, otherwise you cannot run it. The result of the above example is as follows:

+-+ | number | Cloud ID | name | IP address | +-+ | 1 | server01 | Server 01 | 172. 16.0.1 | | 2 | server02 | Server 02 | 172.16.0.2 | | 3 | server03 | Server 03 | 172.16.0.3 | | 4 | server04 | Server 04 | 172.16.0.4 | | 5 | server05 | Server 05 | 172.16.0.5 | | 6 | server06 | Server 06 | 172.16.0.6 | | 7 | server07 | Server 07 | 172.16.0.7 | | | | 8 | server08 | Server 08 | 172.16.0.8 | | 9 | server09 | Server 09 | 172.16.0.9 | +-+ |

The csv file cannot be renamed directly through xls, and an error will be reported. If it is a xls file, please use Save as csv to get the csv file

D, add from sql query value

The data queried from the database can be directly imported into the table print. The following example uses sqlite3. If mysql is used, it is the same. As long as the data can be queried, it can be imported 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)

The running results are as follows:

+-+ | number | Cloud ID | name | IP address | +-+ | 1 | server01 | Server 01 | 172. 16.0.1 | | 2 | server02 | Server 02 | 172.16.0.2 | | 3 | server03 | Server 03 | 172.16.0.3 | | 4 | server04 | Server 04 | 172.16.0.4 | | 5 | server05 | Server 05 | 172.16.0.5 | | 6 | server06 | Server 06 | 172.16.0.6 | | 7 | server07 | Server 07 | 172.16.0.7 | | | | 8 | server08 | Server 08 | 172.16.0.8 | | 9 | server09 | Server 09 | 172.16.0.9 | +-+ |

E. Import data from HTML

Import from html tables is supported, see the following example:

#! / usr/bin/python # * * coding:utf-8** import sys from prettytable import PrettyTable from prettytable import from_html reload (sys) sys.setdefaultencoding ('utf8') html_string=''' number Cloud number name IP address 1 server01 Server 01 172.16.0.1 2 server02 Server 02 172.16.0.2' 'table = from_html (html_string) print (table [0])

The running results are as follows:

+-+ | number | Cloud ID | name | IP address | +-+ | 1 | server01 | Server 01 | 172. 16.0.1 | | 2 | server02 | Server 02 | 172.16.0.2 | +-+

As in the above example, we can import the html table, but the difference is the print statement. When using the html table to import data, print must be the first element in the list, otherwise an error like [] may be reported.

This is because table is not a PrettyTable object, but a list of individual PrettyTable objects. It comes from parsing html, so you cannot print table directly, but you need to print table [0].

5. Table output format

Just as multiple inputs are supported, table output also supports multiple formats, and we have used print output in the above example, which is a common output method.

A 、 print

Print out the form directly through print. A form printed in this way will have a border.

B, output the table in HTML format

Print (table.get_html_string ()) can print out a table of html tags.

In the above example, using print (table.get_html_string ()) prints the following result:

Numbered cloud number name IP address 1 server01 server 01 172.16.0.1 2 server02 server 02 172.16.0.2

6. Selective output

After prettytable creates the table, you can still optionally output certain rows.

A, output the specified column

Print table.get_string (fields= ["number", "IP address"]) can output the specified column

B, output the first two lines

The specified column can be printed through print (table.get_string (start = 0, end = 2)), and of course the start and end parameters give me free control over the display range. Of course, the interval contains start but not end. Are you familiar with this usage?

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

C. Slice the form

From the output interval above, we make a bold assumption that since the interval contains the rule that start does not contain end and sliced, we can not slice to generate a new table and print it.

Actually, it can.

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

As in the above code snippet, we can print out a table of 0 to 1 lines with a total of 2 rows. The slicing function of python is extremely powerful, and with slicing we are free to enter any line.

D, output sort

Sometimes we need to sort the output table, use print table.get_string (sortby= "number", reversesort=True) to sort the table, where reversesort specifies whether to sort in reverse order, the default is False, that is, the default positive sequence sort.

Sortby specifies the fields to sort.

7. The style of the table

A, built-in style

Through set_style () can set table style, prettytable built-in a variety of styles, I think MSWORD_FRIENDLY,PLAIN_COLUMNS,DEFAULT these three styles look refreshing, in the terminal to display the table originally looks very tired, plus a little gaudy things look even more tired.

In addition to the three styles recommended above, there is another style that has to be said, and that is RANDOM, which is a random style, and each print will randomly choose one of the built-in styles, which is more fun.

Specific built-in several styles, please refer to the official website to try to output.

#! / 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 ([' serial number', 'cloud number', 'name','IP address']) table.add_row (['1' '172.16.0.1']) table.add_row ([' 3pm 'server 03' server' '172.16.0.3']) table.add_row ([' 2' server 'server 02'') table.add_row (['9pm' 'server09'' server '09' server' 172.16.0.9']) table.add_row (['4' minute 'server04') ) table.add_row (['5pm /' server05']) table.add_row (['6' / 'server06' /' server / 06' / 172.16.0.6']) table.add_row ([/ /'8' / 'server08' /' server / 08' /'/ 'server / 08' /' server / 08' /') table.add_row (['7') 'server07',' Server 07pm 172.16.0.7]) table.set_style (DEFAULT) print (table)

B, custom style

In addition to the built-in styles, PrettyTable also provides user customization, such as alignment, digital output format, border connectors, and so on

C, set alignment

Align provides a way for the user to set the alignment. The values of lline _ r _ c are convenient for left alignment, right alignment and center alignment. If not set, the default alignment is centered.

D, control the border style

In PrettyTable, a border consists of three parts, a horizontal border, a vertical border, and a border connector (horizontal and vertical link symbols)

The following is an example:

#! / usr/bin/python # * * coding:utf-8** import sys from prettytable import PrettyTable reload (sys) sys.setdefaultencoding ('utf8') table = PrettyTable ([' serial number', 'cloud number', 'name','IP address']) table.add_row (['1Med' server01 'server' server 01' 'server' 172.16.0.1']) table.add_row (['3'' '172.16.0.3') table.add_row ([' 2ZHZ] server02MZ 'server02MZ']) table.add_row (['9MMM09MZ' server09MJ 172.16.0.9']) table.add_row (['4MYOLING' server04M04M05']) table.add_row (['5LING' server 05' 'server 05meme' 172.16.0.5') table.add_row (['6pl' 'server06'' server''172.16.0.6']) table.add_row (['8' 'mince`server08'' server08' 'server' 172.16.0.8']) table.add_row (['7' 'recorder' server07' 'server' 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` controls whether the border is displayed Default is `True

Table.junction_char controls border connectors

Table.horizontal_char controls the horizontal border symbol

Table.vertical_char controls vertical border symbol

The above example runs as follows:

$+ $% No.% Cloud ID% name% IP address $+ $% 1% server01% Server 01% 172.16.0.1%% 3% server03% Server 03% 172.16.0.3%% 2% server02% Server 02% 172.16.0.2%% 9% server09% Server 09% 172.16.0.9% 4% server04% Server 04% 172.16.0.4% 5% server05% Server 05% 172.16.0.5%% 6% server06% Server 06% 172.16.0.6% 8% server08% Server 08% 172.16.0.8% 7% server07% Server 07% 172.16.0.7% $+ $"how to use Python to output beautiful This is the end of the introduction of the table. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report