Выполнение кода при завершении программы python
Как выполнять код после завершения программы от имени пользователя? к примеру: os.remove(‘file.txt’)
Ответы (1 шт):
Автор решения: Stanislav Volodarskiy
→ Ссылка
Используйте try/finally. Даже если случилось исключение блок finally будет исполнен:
import time
try:
while True:
print('press Ctrl-C to stop')
time.sleep(1)
finally:
print('\n\nCleanup code is here\n')
$ python cleanup.py press Ctrl-C to stop press Ctrl-C to stop press Ctrl-C to stop ^C Cleanup code is here Traceback (most recent call last): File "cleanup.py", line 7, in <module> time.sleep(1) KeyboardInterrupt
Можно обработать KeyboardInterrupt чтобы исключение не портило настроение в конце программы:
import time
try:
while True:
print('press Ctrl-C to stop')
time.sleep(1)
except KeyboardInterrupt:
print('\n\nKeyboardInterrupt cleanup code is here')
finally:
print('\n\nCommon cleanup code is here')
$ python cleanup.py press Ctrl-C to stop press Ctrl-C to stop press Ctrl-C to stop ^C KeyboardInterrupt cleanup code is here Common cleanup code is here