If you stop a python script with Ctrl+C, will it execute any finally blocks, or will it literally stop the script where it is?
-
1It kills it where it is – Roman Dec 22 '16 at 09:58
-
I do not understand what your question is meaning. I suggest you to read: http://stackoverflow.com/help/how-to-ask and http://www.catb.org/~esr/faqs/smart-questions.html – Pitto Dec 22 '16 at 10:00
-
1run CTRL+C from MinGW / Windows it just kills the process, doesn't send any keyboard interrupt. But that's a special case. – Jean-François Fabre Dec 22 '16 at 10:01
3 Answers
Well, the answer is mostly it depends. Here is what actually happens:
- Python executes code in a
try:... finally:
block - a Ctrl-C is emitted and is translated in a KeyboardInterrupt Exception
- processing is interrupted and controls passes to the finally block
So at first sight, all works as expected. But...
When a user (not you, but others...) wants to interrupt a task he generally hits multiple times Ctrl-C. The first one will branch execution in the finally
block. If another Ctrl-C occurs in the middle of the finally block because it contains slow operations like closing files, a new KeyboardInterrupt will be raised and nothing guarantees that the whole block will be executed, and you could have something like:
Traceback (most recent call last):
File "...", line ..., in ...
...
KeyboardInterrupt
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "...", line ..., in ...
...
File "...", line ..., in ...
...
KeyboardInterrupt

- 143,923
- 11
- 122
- 252
-
-
with statements and context managers perhaps? https://docs.python.org/3/library/contextlib.html. Or does the same issue apply? – Sterling Aug 19 '22 at 15:22
Yes, assuming a single Ctrl+C, at least under Linux it will. You can test it with the following Python 3 code:
import time
try:
print('In try.')
time.sleep(1000)
finally:
print(' <-- Note the Ctrl+C.')
for i in range(1, 6):
print(f'Finishing up part {i} of 5.')
time.sleep(.1)
Here is the output:
$ ./finally.py
In try.
^C <-- Note the Ctrl+C.
Finishing up part 1 of 5.
Finishing up part 2 of 5.
Finishing up part 3 of 5.
Finishing up part 4 of 5.
Finishing up part 5 of 5.
Traceback (most recent call last):
File "./finally.py", line 7, in <module>
time.sleep(1000)
KeyboardInterrupt

- 57,944
- 17
- 167
- 143
Yes, it will usually raise a KeyboardInterrupt exception, but remember that your application can be unexpectedly terminated at any time, so you shouldn't rely on that.

- 492
- 3
- 14