class Resource():
def __enter__(self):
print('===connect to resource===')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('===close resource connection===')
return True #告诉python解释器异常已处理
return False #告诉python解释器抛出异常
def operate(self):
1/0
import contextlib
@contextlib.contextmanager
def open_func(file_name):
# __enter__方法
print('open file:', file_name, 'in __enter__')
file_handler = open(file_name, 'r')
try:
yield file_handler # yield后相当于__exit__
except Exception as exc:
# deal with exception
raise Exception(str(exc))
print('the exception was thrown: {}'.format(str(exc)))
finally:
print('close file:', file_name, 'in __exit__')
file_handler.close()
return
import os
from functools import partial
file_path = os.path.dirname(os.path.abspath(__file__))
get_file_path = partial(os.path.join, file_path)
print(get_file_path("deploy.sh"))
if __name__ == "__main__":
with open_func(get_file_path("deploy.sh")) as file_in:
for line in file_in:
# 1/0
print(line)
# with Resource() as res:
# res.operate()