使用with语句:记录时间&检查路径

《Python使用with语句:记录时间&检查路径》

  通过这个来理解with语句是如何进行上下文管理的,我们经常使用with语句打开文件,这样可以避免忘记file.close()的情况,但是理解了with语句的调用逻辑后,可以发现利用with可以方便做很多其他的事情,比如记录时间和检查创建路径等常用方法就可以使用with语句来实现了。

Key Words:Python、with、__enter__、__exit__


Beijing, 2020

作者:RaySue

Agile Pioneer  

使用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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值