Using PrettyTable in Python to Display Structured CLI Tables
This article introduces the PrettyTable library for Python, explains how to install it, demonstrates various ways to create and populate tables—including row, column, CSV, database, and HTML sources—covers output formats, selective printing, sorting, and styling options, and provides complete code examples for each feature.
PrettyTable is a Python library that formats data into attractive tables for command‑line interfaces, handling Unicode (including Chinese) gracefully.
Installation : Install via pip install prettytable .
Basic Example (row‑wise creation):
#!/usr/bin/python
# coding:utf-8
import sys
from prettytable import PrettyTable
reload(sys)
sys.setdefaultencoding('utf8')
table = PrettyTable(['编号','云编号','名称','IP地址'])
for i in range(1,10):
table.add_row([str(i), f'server0{i}', f'服务器0{i}', f'172.16.0.{i}'])
print(table)The output shows a bordered table with the four columns.
Adding Data :
Row addition: table.add_row([...]) (list length must match header length).
Column addition: table.add_column('项目', ['编号','云编号','名称','IP地址']) and table.add_column('值', ['1','server01','服务器01','172.16.0.1']) .
CSV import: from prettytable import from_csv fp = open('res.csv','r') table = from_csv(fp) print(table) fp.close()
Database import (SQLite example):
#!/usr/bin/python
# coding:utf-8
import sys, sqlite3
from prettytable import PrettyTable, from_db_cursor
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)HTML import example:
#!/usr/bin/python
# coding:utf-8
import sys
from prettytable import PrettyTable, 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])Output Formats :
Standard print: print(table) (bordered ASCII table).
HTML string: print(table.get_html_string()) .
Selective Output :
Specific columns: print(table.get_string(fields=['编号','IP地址'])) .
Row range: print(table.get_string(start=0, end=2)) (prints rows 0‑1).
Slicing: new_table = table[0:2] print(new_table) .
Sorting: print(table.get_string(sortby='编号', reversesort=True)) .
Styling :
Built‑in styles via table.set_style(DEFAULT) , MSWORD_FRIENDLY , PLAIN_COLUMNS , or random RANDOM .
Custom alignment: table.align[1] = 'l' (left‑align column 1).
Border control: table.border = True , table.junction_char='$' , table.horizontal_char='+' , table.vertical_char='%' .
These options let developers tailor the appearance of CLI tables to suit readability and aesthetic preferences.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.