自定义上下文管理器

import os
import subprocess
import datetime


class CustomFile(object):
"""自定义一个上下文 文件类"""
	def __init__(self, file_name, file_model, *args, **kwargs):
		self.file_name = file_name
		self.file_model = file_model

	def __enter__(self, *args, **kwargs):
		self.my_print("before open file, do something!")
		self.f = open(self.file_name, self.file_model)
		return self.f

	def __exit__(self, *args, **kwargs):
		"""
		__exit__方法有三个参数:exc_type, exc_val, exc_tb。如果代码块BLOCK发生异常并退出,那么分别对应异常的type、value 和 traceback。否则三个参数全为None。
		__exit__方法的返回值可以为True或者False。如果为True,那么表示异常被忽视,相当于进行了try-except操作;如果为False,则该异常会被重新raise。
		"""
		self.my_print(args)
		self.my_print("before close , do something!")
		self.f.close()

	@classmethod
	def my_print(cls, *args):
		print('当前时间:{}'.format(datetime.datetime.now()), *args)


temp_file = './temp_file'
if not os.path.exists(temp_file):
	subprocess.getoutput('echo "hello world" >> {}'.format(temp_file))

CustomFile.my_print('start')
with CustomFile(temp_file, 'r') as file:
	data = file.read()
	CustomFile.my_print(data)
CustomFile.my_print('end')


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值