Выполняется определенный код при завершении команды через ctrl + c
Какие есть способы реализации данной идеи, кроме как поместить весь код в
try:
обычный код
except KeyboardInterrupt:
код при завершении програмы через ctrl + c
Ответы (1 шт):
Автор решения: vadim vaduxa
→ Ссылка
import sys, contextlib
def main(a) -> bool:
print('обычный код %s' % a)
raise KeyboardInterrupt
raise ZeroDivisionError('err')
return True
def excepthook(*args):
la = len(args)
if la == 3:
(exc_type, exc_val, exc_tb) = args
elif la == 1:
(exc_type, exc_val, exc_tb) = (type(args[0]), args[0], args[0].__traceback__)
elif not la:
(exc_type, exc_val, exc_tb) = sys.exc_info()
else:
raise AssertionError(args)
if exc_type == KeyboardInterrupt:
print('код при завершении програмы через ctrl + c')
raise
else:
raise exc_type(exc_val).with_traceback(exc_tb)
def test():
try: raise UserWarning('ex')
except Exception as e:
try: excepthook(e)
except UserWarning:
try: excepthook()
except UserWarning:
try: excepthook(e, e)
except AssertionError: print('ok')
else: print('-1')
else: print('-2')
else: print('-3')
if __name__ == '__main__':
test()
sys.excepthook = excepthook
# with contextlib.suppress(UserWarning, KeyboardInterrupt):
main(1)
# b = False
# with contextlib.suppress(UserWarning, KeyboardInterrupt):
# b = main(2)
# if not b:
# sys.exit()
print('-')