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?
You can handle CTRL + C by catching the KeyboardInterrupt exception. You can implement any clean-up code in the exception handler.
The finally block will be executed no matter if the try block raises an error or not. This can be useful to close objects and clean up resources.
kill -SIGKILL will prevent finally blocks from running. SIGTERM and SIGHUP will also prevent finally blocks from running unless you install a handler to control the shutdown yourself; by default, Python does not handle SIGTERM or SIGHUP . An exception in finally can prevent cleanup from completing.
finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block. finally block is used to deallocate the system resources.
Well, the answer is mostly it depends. Here is what actually happens:
try:... finally:
blockSo 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With