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')
自定义上下文管理器
最新推荐文章于 2022-05-04 07:44:10 发布