很多时候我们的脚本输出都是列表或字典形式,prettytable可以将输出内容以表格方式输出。
安装
通过pip安装
复制
1 | pip install prettytable |
使用
示例:
复制
1 2 3 4 5 6 7 8 9 10 | >>> from prettytable import PrettyTable >>> table = PrettyTable() >>> table.field_names = ['Name', 'Age', 'Country'] >>> table.add_row(['Len', '56', 'SZ']) >>> print(table) +------+-----+---------+ | Name | Age | Country | +------+-----+---------+ | Len | 56 | SZ | +------+-----+---------+ |
将mysql输出以表格化输出:
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import pymysql from prettytable import from_db_cursor conn = pymysql.connect(host='localhost',user='root',password='',port=3306,database='test') cursor = conn.cursor() sql='select * from Repo' cursor.execute(sql) table = from_db_cursor(cursor) print(table) 输出: +----+--------------------------------------+ | id | repo_id | +----+--------------------------------------+ | 2 | 6388e412-b92e-4881-a328-87cf7f57ba4a | | 4 | b7c49526-771e-4c70-85e1-a19f031bf02e | | 1 | d3ed022a-cca5-4481-a605-01108290a9a4 | | 5 | e83c548e-b559-4d81-a911-42a7fce2b7b7 | +----+--------------------------------------+ |
结束
prettytable还有其它用法,比如从csv或html添加数据并输出,详细请看文档。