網站首頁 編程語言 正文
一、python logging日志模塊簡單封裝
項目根目錄創建 utils/logUtil.py
import logging
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
class Log(object):
STAND = "stand" # 輸出到控制臺
FILE = "file" # 輸出到文件
ALL = "all" # 輸出到控制臺和文件
def __init__(self, mode=STAND):
self.LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
self.logger = logging.getLogger()
self.init(mode)
def debug(self, msg):
self.logger.debug(msg)
def info(self, msg):
self.logger.info(msg)
def warning(self, msg):
self.logger.warning(msg)
def error(self, msg):
self.logger.error(msg)
def init(self, mode):
self.logger.setLevel(logging.DEBUG)
if mode == "stand":
# 輸出到控制臺 ------
self.stand_mode()
elif mode == "file":
# 輸出到文件 --------
self.file_mode()
elif mode == "all":
# 輸出到控制臺和文件
self.stand_mode()
self.file_mode()
def stand_mode(self):
stand_handler = logging.StreamHandler()
stand_handler.setLevel(logging.DEBUG)
stand_handler.setFormatter(logging.Formatter(self.LOG_FORMAT))
self.logger.addHandler(stand_handler)
def file_mode(self):
'''
filename:日志文件名的prefix;
when:是一個字符串,用于描述滾動周期的基本單位,字符串的值及意義如下:
“S”: Seconds
“M”: Minutes
“H”: Hours
“D”: Days
“W”: Week day (0=Monday)
“midnight”: Roll over at midnight
interval: 滾動周期,單位有when指定,比如:when='D',interval=1,表示每天產生一個日志文件;
backupCount: 表示日志文件的保留個數;
'''
# 輸出到文件 -----------------------------------------------------------
# 按文件大小輸出
# file_handler = RotatingFileHandler(filename="my1.log", mode='a', maxBytes=1024 * 1024 * 5, backupCount=10, encoding='utf-8') # 使用RotatingFileHandler類,滾動備份日志
# 按時間輸出
file_handler = TimedRotatingFileHandler(filename="my.log", when="D", interval=1, backupCount=10,
encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter(self.LOG_FORMAT))
self.logger.addHandler(file_handler)
log = Log(mode=Log.STAND)
使用方法:
from utils.logUtil import log
if __name__ == '__main__':
log.debug("debug msg")
log.info("info msg")
log.warning("warning msg")
log.error("error msg")
跑一下測試結果:
二、pandas編寫命令行腳本操作excel的小tips
這里用上面日志小工具
如果不想用這個,可以把日志輸出的代碼換成 print() 或者刪掉
1、tips
1.1使用說明格式
# 使用說明 -----------------------------------
time.sleep(1)
print('===========================================================')
print('簡單說明:使用正則表達式拆分excel表中不規范的作者,初步提取對應需求字段')
print('PS:')
print('1.文件夾下需要有一個excel(只放一個,名稱隨意),其中一列“作者”保存著待拆分的作者')
print('2.拆分后的excel將新增幾列拆分結果列,以 <作者>[拆分] 作為列名標記')
print('===========================================================')
time.sleep(1)
# ------------------------------------------
1.2接收操作目錄方法
# 輸入操作路徑 ----------------------------------------------------------------
operate_dir = input('請輸入excel目錄(旺柴):') # D:\PycharmProjects\spiders\圖片下載工具\excel
operate_dir = os.path.abspath(operate_dir)
# operate_dir = os.path.abspath(r'C:\Users\cxstar46\Desktop\正則表達式題名拆分測試')
# -----------------------------------------------------------------------------
1.3檢測并讀取目錄下的excel,并限制當前目錄只能放一個excel
# 檢測excel數量,只能放一個,當只有一個excel時,提取它的路徑excel_path -------
log.info('檢查路徑下的文件格式...')
excel_name = None
excel_count = 0
file_list = os.listdir(operate_dir)
for file in file_list:
if file.endswith('.xlsx') or file.endswith('.xlx'):
excel_count += 1
excel_name = file
if excel_count == 0:
log.error('文件夾下沒有excel')
input('按任意鍵退出...')
raise Exception(0)
if excel_count > 1:
log.error("無法讀取excel,文件夾下有多個excel,或者excel未關閉")
input('按任意鍵退出...')
raise Exception(0)
# print(excel_name)
# raise Exception(1212)
# ----------------------------------------------------------------------
# print(excel_path)
# print(img_dir)
# 讀取excel ----------------------------------------
excel_path = os.path.join(operate_dir, excel_name)
# print(excel_path)
try:
df = pd.read_excel(excel_path)
df = df.where(df.notnull(), None)
except Exception as e:
log.error(e)
log.error('文件不存在或已損壞...')
input('按任意鍵退出...')
raise Exception(0)
# -------------------------------------------------
# 打印excel行數
print(df.shape[0])
1.4備份excel
# 備份原始excel表 --------------------------------------------------------------
log.info('備份excel...')
bak_dir = '封面上傳前的備份' # 備份文件夾的名稱
file_list = os.listdir(operate_dir)
if bak_dir not in file_list:
os.makedirs(os.path.join(operate_dir, bak_dir))
bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), "{}_{}".format(datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), excel_name))
shutil.copyfile(excel_path, bak_excel_path)
# -----------------------------------------------------------------------------
1.5報錯暫停,并顯示異常信息
try:
raise Exception("執行業務報錯")
except Exception as e:
import traceback
log.error(traceback.format_exc()) # 記錄異常信息
input('執行完畢,按任意鍵繼續...')
1.6判斷excel是否包含某列,不包含就新建
cover_ruid_col_name = "封面ruid"
# 沒有封面ruid這一列就創建
if cover_ruid_col_name not in df.columns.values:
df.loc[:, cover_ruid_col_name] = None
1.7進度展示與階段保存
# 讀取excel
excel_path = './封面上傳測試.xlsx'
df = pd.read_excel(excel_path)
review_col = "審核結果"
# 沒有“審核結果”這一列就創建
if review_col not in df.columns.values:
df.loc[:, review_col] = None
for i in range(df.shape[0]):
# 打印進度 ---------------------------------------------
log.info("----------------------------------")
log.info("當前進度: {} / {}".format(i+1, df.shape[0]))
# ----------------------------------------------------
# 執行表格插入業務
# 判斷業務
# 吧啦吧啦
# 業務執行結果插入原表
df.loc[i, "審核結果"] = "好耶"
# 階段性保存 ----------------------------
save_space = 200 # 每執行兩百行保存一次
if i+1 % save_space == 0 and i != 0:
df.to_excel(excel_path, index=0)
log.info("階段性保存...")
# -------------------------------------
原文鏈接:https://blog.csdn.net/weixin_43721000/article/details/126016051
相關推薦
- 2022-06-07 ASP.NET?Core應用啟動Startup類簡介_基礎應用
- 2022-08-26 淺談C++/C關于#define的那些奇奇怪怪的用法_C 語言
- 2022-11-21 Pandas數據分析之groupby函數用法實例詳解_python
- 2023-04-26 C語言函數調用基礎應用詳解_C 語言
- 2023-04-19 TypeError [ERR_INVALID_ARG_TYPE]: The “path“ argum
- 2022-09-08 pytorch中Tensor.to(device)和model.to(device)的區別及說明_p
- 2022-06-02 C語言的模板與泛型編程你了解嗎_C 語言
- 2022-08-16 C#獲取Description特性的擴展類詳解_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支