I am trying to save big data in SQL using sqlite3 in python, I want to test the result but no need to save all the data, if I try to press ctrl+c, I got this error: KeyboardInterrupt. How can I stop the code without getting errors?
1 Answers
How can I stop the code without getting errors?
Use a try-catch
block:
try:
...
# do your SQL writes here
except KeyboardInterrupt:
# cleanup and exit the program
There is a caveat with catching KeyboardInterrupt
, which is very relevant in your situation:
Catching a
KeyboardInterrupt
requires special consideration. Because it can be raised at unpredictable points, it may, in some circumstances, leave the running program in an inconsistent state. It is generally best to allowKeyboardInterrupt
to end the program as quickly as possible or avoid raising it entirely. (See Note on Signal Handlers and Exceptions.)
It is important to pay attention to this because you will be doing database writes and if a write is interrupted mid way, you could render your table unusable.
Using signal handlers instead of try-catch
An alternative (and recommended alternative) to catching the exception is to instead use a signal handler to handle the SIGINT
signal. See How do I capture SIGINT in Python?

- 39,374
- 15
- 132
- 179