How to Turn CLI Output into Beautiful Tables with Python’s PrettyTable
This tutorial shows how to use the Python PrettyTable library to format command‑line data into readable tables, covering installation, basic usage, adding rows or columns, importing from CSV, databases or HTML, customizing output formats, selective printing, sorting, and styling options.
Introduction
When building a Linux‑based command‑line tool in Python to manage resources such as Alibaba Cloud ECS, plain text output can become hard to read. Using PrettyTable allows you to display data in a clean, tabular format with good Chinese character support.
Installation
pip install prettytableBasic 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'])
# ... add more rows ...
print(table)The command prints a bordered table with the specified headers and rows.
Adding Data
Row‑wise using add_row (as in the basic example). The list length must match the header length.
Column‑wise using add_column:
#!/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)From CSV with from_csv:
#!/usr/bin/python
# coding:utf-8
import sys
from prettytable import PrettyTable, from_csv
reload(sys)
sys.setdefaultencoding('utf8')
fp = open('res.csv', 'r')
table = from_csv(fp)
print(table)
fp.close()From a DB cursor with from_db_cursor (e.g., SQLite):
#!/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)From HTML with from_html:
#!/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(table) prints a bordered ASCII table. To get HTML output use print(table.get_html_string()).
Selective Output
Print specific columns: print(table.get_string(fields=['编号','IP地址'])) Print a range of rows: print(table.get_string(start=0, end=2)) (end is exclusive).
Slice the table like a list: new_table = table[0:2]; print(new_table) Sort rows:
print(table.get_string(sortby='编号', reversesort=True))Styling
PrettyTable provides built‑in styles such as MSWORD_FRIENDLY, PLAIN_COLUMNS, DEFAULT, and RANDOM. Set a style with table.set_style(style).
Custom styling options include alignment ( l, r, c), border visibility, and characters for borders, junctions, horizontal and vertical lines:
table.align[1] = 'l'
table.border = True
table.junction_char = '$'
table.horizontal_char = '+'
table.vertical_char = '%'
print(table)Conclusion
PrettyTable offers a flexible way to present command‑line data as readable tables, with many input sources, output formats, selective printing, sorting, and styling capabilities. For more details see the official repository: https://github.com/jazzband/prettytable .
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
