, , , , .
import time
from contextlib import contextmanager
NUMBER_OF_EXCEPTIONS = 0
class Timer(object):
def __init__(self):
self.t1 = time.time()
def stop(self):
self.t2 = time.time()
self.elapsed = self.t2 - self.t1
@contextmanager
def profiler():
t = Timer()
yield t
t.stop()
print("elapsed: ", t.elapsed)
with profiler():
try:
1/0
except ZeroDivisionError:
NUMBER_OF_EXCEPTIONS += 1
time.sleep(1.1)
with profiler():
try:
1/2
except ZeroDivisionError:
NUMBER_OF_EXCEPTIONS += 1
time.sleep(1.1)
print("Total handled exceptions: ", NUMBER_OF_EXCEPTIONS)
:
elapsed: 1.10120511055
elapsed: 4.05311584473e-06
Total handled exceptions: 1
, - , (source). :
NUMBER_OF_EXCEPTIONS = 0
@contextmanager
def handle_zero_division_error():
try:
yield
except ZeroDivisionError as err:
global NUMBER_OF_EXCEPTIONS
NUMBER_OF_EXCEPTIONS += 1
time.sleep(1.1)
with profiler():
with handle_zero_division_error():
1/0
with profiler():
with handle_zero_division_error():
1/0
with profiler(), handle_zero_division_error():
1/2
print("Total handled exceptions: ", NUMBER_OF_EXCEPTIONS)
:
elapsed: 1.10123705864
elapsed: 1.10085892677
elapsed: 1.90734863281e-05
Total handled exceptions: 2