《Python使用with语句:记录时间&检查路径》
通过这个来理解with语句是如何进行上下文管理的,我们经常使用with语句打开文件,这样可以避免忘记file.close()的情况,但是理解了with语句的调用逻辑后,可以发现利用with可以方便做很多其他的事情,比如记录时间和检查创建路径等常用方法就可以使用with语句来实现了。
Key Words:Python、with、__enter__、__exit__
Beijing, 2020
作者:RaySue
使用with语句记录时间
# coding:utf-8
# @Time : 23/08/2018 16:49
# @Author : SuRui
import time
class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # milliseconds
if self.verbose:
print('Elapsed time: %4.2f ms' % self.msecs)
@property
def time_used(self):
return round(self.msecs, 4)
if __name__ == "__main__":
with Timer(True) as t:
time.sleep(1)
print(t.time_used)
使用with语句检查路径
import os
class CheckDirsExist:
"""
Check [dir1, dir2 ...] is exist or not, if not then create them.
"""
def __init__(self, dir_path_list):
self.dir_path_list = dir_path_list
self.DirsExistFlag = [False] * self.num
def __enter__(self, *args):
for i in range(self.num):
if os.path.exists(self.dir_path_list[i]):
self.DirsExistFlag[i] = True
return self
def __exit__(self, *args):
for i in range(self.num):
if not self.DirsExistFlag[i]:
os.makedirs(self.dir_path_list[i])
@property
def num(self):
return len(self.dir_path_list)
def __call__(self, *args, **kwargs):
for i in range(self.num):
if not self.DirsExistFlag[i]:
print("<%s> is creating ..." % self.dir_path_list[i])
else:
print("<%s> is alreay exists." % self.dir_path_list[i])
if __name__ == "__main__":
with CheckDirsExist(["./xxx", "./xxx1", "./xxx2"]) as check: check()