Вот простой фрагмент кода, иллюстрирующий мои мысли:
Код: Выделить всё
class MyContext:
def __init__(self, name):
self.name = name
def __enter__(self):
print(f'Entering context {self.name}')
return self
def __exit__(self, exc_type, exc_value, traceback):
print(f'Exiting context {self.name}')
time.sleep(5)
print(f'Exited context {self.name}')
def process_name(name):
with MyContext(name):
print(f'Processing {name}')
time.sleep(100)
print(f'Finished {name}')
names = ['Alice', 'Bob']
for name in names:
process_name(name)
Код: Выделить всё
Entering context Alice
Processing Alice
Entering context Bob
Processing Bob
^CExiting context Alice
Exiting context Bob
Exited context Alice
Exited context Bob
KeyboardInterrupt (maybe multiple times)
Код: Выделить всё
Entering context Alice
Processing Alice
Entering context Bob
Processing Bob
^CExiting context Alice
Exiting context Bob
KeyboardInterrupt
Подробнее здесь: https://stackoverflow.com/questions/792 ... -gracefull
Мобильная версия