如果某个函数实现很长, 有时候希望把函数分割成若干部分, 并且可以折叠, 执行时能够打印日志. 可以采用下面的办法来实现:
from mylog import logger
import time
class MyTask:
def __init__(self,task:str) -> None:
self.task:str = task
self.start_time = time.time()
def __enter__(self):
logger.trace(f'开始执行: {self.task} ...')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
end_time = time.time()
spend_time = round(end_time - self.start_time,2)
if not exc_type: logger.success(f'执行完毕({spend_time}s): {self.task}')
else: logger.error(f'执行失败({spend_time}s): {self.task}')
return False # 如果有异常, 继续抛出异常
def run():
with MyTask('task1') as task1:
print('task1')
with MyTask('task2') as task1:
print('task2')
run()
打印如下信息: