-1

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?

mansour32
  • 1
  • 4
  • how are you inserting data. line by line bulk .... – nbk Jun 16 '22 at 22:59
  • Why does it matter if your interpreter acknowledges the fact that you triggered a `KeyboardInterrupt`, exactly? That's exactly what CTRL+C does... – esqew Jun 16 '22 at 23:06

1 Answers1

0

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 allow KeyboardInterrupt 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?

smac89
  • 39,374
  • 15
  • 132
  • 179