1

Как выполнять код после завершения программы от имени пользователя? к примеру: os.remove(‘file.txt’)

2
  • "выполнять код после завершения программы"?
    – Jack_oS
    26 дек 2020 в 20:03
  • Может просто дописать эту строчку в самый конец программы? 26 дек 2020 в 20:28

1 ответ 1

2

Используйте 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

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.