PrettyTable 是python中的一個第三方庫,可用來生成美觀的ASCII格式的表格,十分實用。html
pip install prettytable
from prettytable import from_csv fp = open("mytable.csv", "r") pt = from_csv(fp) fp.close()
from prettytable import from_html pts = from_html(html_string)
from prettytable import from_db_cursor db_cur.execute("SELECT * FROM mytable") pt = from_db_cursor(db_cur)
##按行添加數據 tb = pt.PrettyTable() tb.field_names = ["City name", "Area", "Population"] # 字段名 tb.add_row(["A1",125, 1158259]) # 增長行 tb.add_row(["B1",595, 1857594]) tb.add_row(["C1", 12, 120900]) tb.add_row(["D1", 135, 205556]) print(tb)
結果python
+-----------+------+------------+ | City name | Area | Population | +-----------+------+------------+ | A1 | 125 | 1158259 | | B1 | 595 | 1857594 | | C1 | 12 | 120900 | | D1 | 135 | 205556 | +-----------+------+------------+
## 按列添加數據 tb.add_column('index',[1,2,3,4]) print(tb)
輸出結果sql
+-----------+------+------------+-------+ | City name | Area | Population | index | +-----------+------+------------+-------+ | A1 | 125 | 1158259 | 1 | | B1 | 595 | 1857594 | 2 | | C1 | 12 | 120900 | 3 | | D1 | 135 | 205556 | 4 | +-----------+------+------------+-------+
## 使用不一樣的輸出風格 tb.set_style(pt.MSWORD_FRIENDLY) print('--- style:MSWORD_FRIENDLY -----') print(tb) tb.set_style(pt.PLAIN_COLUMNS) print('--- style:PLAIN_COLUMNS -----') print(tb) ## 隨機風格,每次不一樣 tb.set_style(pt.RANDOM) print('--- style:RANDOM-----') print(tb) tb.set_style(pt.DEFAULT) print('--- style:DEFAULT -----') print(tb)
輸出結果數據庫
--- style:MSWORD_FRIENDLY ----- | City name | Area | Population | | A1 | 125 | 1158259 | | B1 | 595 | 1857594 | | C1 | 12 | 120900 | | D1 | 135 | 205556 | --- style:PLAIN_COLUMNS ----- City name Area Population A1 125 1158259 B1 595 1857594 C1 12 120900 D1 135 205556 --- style:RANDOM----- City name Area Population A1 125 1158259 B1 595 1857594 C1 12 120900 D1 135 205556 --- style:DEFAULT ----- +-----------+------+------------+ | City name | Area | Population | +-----------+------+------------+ | A1 | 125 | 1158259 | | B1 | 595 | 1857594 | | C1 | 12 | 120900 | | D1 | 135 | 205556 | +-----------+------+------------+
# 不打印,獲取表格字符串 s = tb.get_string() print(s) # 寫入到文件 with open('1.txt', 'a+') as f: f.write(tb.get_string()) # 能夠只獲取指定列或行 s = tb.get_string(fields=["City name", "Population"],start=1,end=4) print(s)
輸出結果緩存
+-----------+------+------------+ | City name | Area | Population | +-----------+------+------------+ | A1 | 125 | 1158259 | | B1 | 595 | 1857594 | | C1 | 12 | 120900 | | D1 | 135 | 205556 | +-----------+------+------------+ +-----------+------------+ | City name | Population | +-----------+------------+ | B1 | 1857594 | | C1 | 120900 | | D1 | 205556 | +-----------+------------+
## 自定義表格輸出樣式 ### 設定左對齊 tb.align = 'l' ### 設定數字輸出格式 tb.float_format = "2.2" ### 設定邊框鏈接符爲'*" tb.junction_char = "*" ### 設定排序列 tb.sortby = "Population" ### 設定排序方式 tb.reversesort=True ### 設定左側不填充空白字符 tb.left_padding_width = 0 print(tb)
輸出結果數據結構
*----------*-----*-----------* |City name |Area |Population | *----------*-----*-----------* |B1 |595 |1857594 | |C1 |12 |120900 | |A1 |125 |115825.90 | |D1 |135 |20555.60 | *----------*-----*-----------*
## 不顯示邊框 tb.border = 0 print(tb) ## 修改邊框分隔符 tb.set_style(pt.DEFAULT) tb.horizontal_char = '+' print(tb)
輸出結果oracle
City name Area Population B1 595 1857594 C1 12 120900 A1 125 115825.90 D1 135 20555.60 +++++++++++++++++++++++++++++++++ | City name | Area | Population | +++++++++++++++++++++++++++++++++ | B1 | 595 | 1857594 | | C1 | 12 | 120900 | | A1 | 125 | 115825.90 | | D1 | 135 | 20555.60 | +++++++++++++++++++++++++++++++++
#prettytable也支持輸出HTML代碼
s = tb.get_html_string() print(s)
輸出結果app
<table> <tr> <th>City name</th> <th>Area</th> <th>Population</th> </tr> <tr> <td>B1</td> <td>595</td> <td>1857594</td> </tr> <tr> <td>C1</td> <td>12</td> <td>120900</td> </tr> <tr> <td>A1</td> <td>125</td> <td>115825.90</td> </tr> <tr> <td>D1</td> <td>135</td> <td>20555.60</td> </tr> </table>
# 1 x = PrettyTable() x.border = False x.header = False x.padding_width = 5 # 2 x = PrettyTable(border=False, header=False, padding_width=5) # 1 print(x.get_string(align="l")) # 2 x.align["City name"] = "l" x.align["Population"] = "c" x.align["Area"] = "r" # 3 x.align="l"
Oracle_utils.py
# 用於以清晰、可讀的形式輸出 Python 數據結構 from sys import modules import sys import os import cx_Oracle from DBUtils.PooledDB import PooledDB BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) # 加入環境變量 from utils import settings from utils import my_logset from utils.Time_utils import run_time """ 經過PooledDB鏈接Oracle,並完成經常使用一些操做 """ class Ora_util(object): __pool = None # 鏈接池對象 _db_info = { 'user': settings.DB_USER, 'pwd': settings.DB_PASSWORD, 'dsn': settings.DB_SID } def __init__(self, db_info=_db_info, arraysize=500): # 日誌 self.db_log = my_logset.get_mylogger("oradb_access") self.db_info = db_info self.conn = Ora_util.__getConn(db_info) self.cursor = self.conn.cursor() # 每次從數據庫向Python的緩存返回arraysize=100條記錄 self.cursor.arraysize = arraysize @staticmethod def __getConn(db_info): # 靜態方法,從鏈接池中取出鏈接 if Ora_util.__pool is None: __pool = PooledDB(cx_Oracle, user=db_info['user'], password=db_info['pwd'], dsn=db_info['dsn'], mincached=20, maxcached=50) return __pool.connection() # 執行sql @run_time def execute(self, sql, args={}): try: self.db_log.debug('execute sql: {}'.format(sql)) return self.cursor.execute(sql, args) except Exception as e: self.close() raise e # oracle的參數名必須使用:代替,如 userid = :userid def insertOne(self, table, column_dict): column_dict = self.create_params(table, column_dict) keys = ','.join(column_dict.keys()) values = column_dict.values() placeholder = ','.join([':%s' % (v) for v in column_dict.keys()]) ins_sql = 'INSERT INTO %(table)s (%(keys)s) VALUES (%(placeholder)s)' # print(ins_sql % locals()) self.execute(ins_sql % locals(), column_dict) # 獲取序列的下一個值,傳入sequence的名稱 def nextval(self, seq): self.cursor.execute("SELECT %(seq)s.nextval from dual " % locals()) result = self.cursor.fetchall() return result[0][0] # 批量插入數據庫,參數一:表名,參數二:['字段1','字段2',...],參數二:[('值1','值2',...),('值1','值2',...)] def insertMany(self, table, columns=[], values=[]): keys = ','.join(columns) placeholder = ','.join([':%s' % (v) for v in columns]) ins_sql = 'INSERT INTO %(table)s (%(keys)s) VALUES(%(placeholder)s)' self.executemany(ins_sql % locals(), values) return self._get_rows_num()
test.pysocket
import os import sys from sys import modules from prettytable import PrettyTable BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) # 加入環境變量 from utils.Oracle_utils import Ora_util if __name__ == '__main__': ora = Ora_util() ora.execute("DROP TABLE python_modules PURGE") create_table = """ CREATE TABLE python_modules ( module_name VARCHAR2(50) NOT NULL, file_path VARCHAR2(300) NOT NULL, t_id INT NOT NULL ) """ # 執行建立表 create_flag = ora.execute(create_table) # 獲得表全部列 print(ora.get_columns('python_modules')) # 添加模塊信息 M = [] count = 1 for m_name, m_info in modules.items(): try: M.append((m_name, m_info.__file__, count)) count += 1 except AttributeError: pass print(len(M)) print(ora.insertMany('python_modules',['module_name', 'file_path','t_id'],M)) ora.commit() from prettytable import from_db_cursor tb = from_db_cursor(ora.execute('select * from python_modules')) ### 設定左對齊 tb.align = 'l' ### 設定T_ID右對齊 tb.align["T_ID"]="r" ### 設定數字輸出格式 tb.float_format = "2.2" ### 設定邊框鏈接符爲'*" tb.junction_char = "*" ### 設定排序列 tb.sortby = "T_ID" ### 設定排序方式 tb.reversesort = True ### 設定左側不填充空白字符 tb.left_padding_width = 0 print(tb)
輸出結果
[2018-05-31 12:02:07 - DEBUG - oradb_access - Oracle_utils.py - execute- 99 ] execute sql: DROP TABLE python_modules PURGE [2018-05-31 12:02:07 - DEBUG - runtime - Time_utils.py - decor- 51 ] func execute run 0.1400 s [2018-05-31 12:02:07 - DEBUG - oradb_access - Oracle_utils.py - execute- 99 ] execute sql: CREATE TABLE python_modules ( module_name VARCHAR2(50) NOT NULL, file_path VARCHAR2(300) NOT NULL, t_id INT NOT NULL ) [2018-05-31 12:02:08 - DEBUG - runtime - Time_utils.py - decor- 51 ] func execute run 0.0620 s [2018-05-31 12:02:08 - DEBUG - oradb_access - Oracle_utils.py - execute- 99 ] execute sql: select lower(column_name) column_name from user_tab_columns where table_name=upper('python_modules') [2018-05-31 12:02:08 - DEBUG - runtime - Time_utils.py - decor- 51 ] func execute run 0.0030 s [2018-05-31 12:02:08 - DEBUG - oradb_access - Oracle_utils.py - executemany- 139 ] executemany sql:INSERT INTO python_modules (module_name,file_path,t_id) VALUES(:module_name,:file_path,:t_id) ['module_name', 'file_path', 't_id'] [2018-05-31 12:02:08 - DEBUG - runtime - Time_utils.py - decor- 51 ] func executemany run 0.0650 s [2018-05-31 12:02:08 - DEBUG - oradb_access - Oracle_utils.py - execute- 99 ] execute sql: select * from python_modules [2018-05-31 12:02:08 - DEBUG - runtime - Time_utils.py - decor- 51 ] func execute run 0.0090 s *------------------------------*-------------------------------------------------------------------------*-----* |MODULE_NAME |FILE_PATH |T_ID | *------------------------------*-------------------------------------------------------------------------*-----* |utils.Time_utils |C:\Users\china\PycharmProjects\python_utils\utils\Time_utils.py | 87 | |queue |C:\Program Files\Python36\lib\queue.py | 86 | |_compat_pickle |C:\Program Files\Python36\lib\_compat_pickle.py | 85 | |struct |C:\Program Files\Python36\lib\struct.py | 84 | |pickle |C:\Program Files\Python36\lib\pickle.py | 83 | |select |C:\Program Files\Python36\DLLs\select.pyd | 82 | |selectors |C:\Program Files\Python36\lib\selectors.py | 81 | |_socket |C:\Program Files\Python36\DLLs\_socket.pyd | 80 | |socket |C:\Program Files\Python36\lib\socket.py | 79 | |logging.handlers |C:\Program Files\Python36\lib\logging\handlers.py | 78 | |string |C:\Program Files\Python36\lib\string.py | 77 | |logging |C:\Program Files\Python36\lib\logging\__init__.py | 76 | |utils.my_logset |C:\Users\china\PycharmProjects\python_utils\utils\my_logset.py | 75 | |utils.settings |C:\Users\china\PycharmProjects\python_utils\utils\settings.py | 74 | |DBUtils.SteadyDB |C:\Program Files\Python36\lib\site-packages\DBUtils\SteadyDB.py | 73 | |token |C:\Program Files\Python36\lib\token.py | 72 | |tokenize |C:\Program Files\Python36\lib\tokenize.py | 71 | |linecache |C:\Program Files\Python36\lib\linecache.py | 70 | |traceback |C:\Program Files\Python36\lib\traceback.py | 69 | |threading |C:\Program Files\Python36\lib\threading.py | 68 | |DBUtils.PooledDB |C:\Program Files\Python36\lib\site-packages\DBUtils\PooledDB.py | 67 | |DBUtils |C:\Program Files\Python36\lib\site-packages\DBUtils\__init__.py | 66 | |cx_Oracle |C:\Program Files\Python36\lib\site-packages\cx_Oracle.cp36-win_amd64.pyd | 65 | |_decimal |C:\Program Files\Python36\DLLs\_decimal.pyd | 64 | |numbers |C:\Program Files\Python36\lib\numbers.py | 63 | |decimal |C:\Program Files\Python36\lib\decimal.py | 62 | |datetime |C:\Program Files\Python36\lib\datetime.py | 61 | |utils.Oracle_utils |C:\Users\china\PycharmProjects\python_utils\utils\Oracle_utils.py | 60 | |_markupbase |C:\Program Files\Python36\lib\_markupbase.py | 59 | |html.parser |C:\Program Files\Python36\lib\html\parser.py | 58 | |html.entities |C:\Program Files\Python36\lib\html\entities.py | 57 | |html |C:\Program Files\Python36\lib\html\__init__.py | 56 | |unicodedata |C:\Program Files\Python36\DLLs\unicodedata.pyd | 55 | |textwrap |C:\Program Files\Python36\lib\textwrap.py | 54 | |bisect |C:\Program Files\Python36\lib\bisect.py | 53 | |_hashlib |C:\Program Files\Python36\DLLs\_hashlib.pyd | 52 | |hashlib |C:\Program Files\Python36\lib\hashlib.py | 51 | |random |C:\Program Files\Python36\lib\random.py | 50 | |sre_constants |C:\Program Files\Python36\lib\sre_constants.py | 49 | |sre_parse |C:\Program Files\Python36\lib\sre_parse.py | 48 | |sre_compile |C:\Program Files\Python36\lib\sre_compile.py | 47 | |enum |C:\Program Files\Python36\lib\enum.py | 46 | |re |C:\Program Files\Python36\lib\re.py | 45 | |csv |C:\Program Files\Python36\lib\csv.py | 44 | |copyreg |C:\Program Files\Python36\lib\copyreg.py | 43 | |copy |C:\Program Files\Python36\lib\copy.py | 42 | |prettytable |C:\Program Files\Python36\lib\site-packages\prettytable.py | 41 | |encodings.cp437 |C:\Program Files\Python36\lib\encodings\cp437.py | 40 | |contextlib |C:\Program Files\Python36\lib\contextlib.py | 39 | |importlib.machinery |C:\Program Files\Python36\lib\importlib\machinery.py | 38 | |importlib.abc |C:\Program Files\Python36\lib\importlib\abc.py | 37 |