File I/O나 Network I/o는 with 문의 통해서 우리가 원하는 로직을 추가하고 해당 패턴을 통해서 우리가 원하는 클래스를 구현할 수 있다.
import time
class ExcuteTimer():
def __init__(self, message):
self._msg = message
def __enter__(self):
self._start = time.monotonic() #숫자 형태로 시간을 가져옴
return self._start
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type: # 예외가 발생함
print('Logging exception {}'.format((exc_type, exc_val, exc_tb)))
else:
print('{} : {} s'.format(self._msg, time.monotonic() - self._start))
return True
with ExcuteTimer('Start! job') as v:
print('Received start monotionic1 : {}'.format(v))
# Excute job
for i in range(1000000):
pass
raise Exception('Raise Exception!') # 강제로 발생
예외를 지워보고 예를 채워보고 작업을 해보자.