Is it considered good practice to catch a KeyboardInterrupt in Python code?

622 views Asked by At

I was working on a project recently that requires me to be writing data to and from files and I don't want to have to worry about files being corrupted if the script gets stopped via Ctrl+C.

Now, this can be helped by making sure that files are open as little as possible, but you there is always a chance of a random SIGINT happening during a crucial write.

So, I looked into catching the exception (since pressing Ctrl+C results in a KeyboardInterrupt exception) and came across two questions (Capture keyboardinterrupt in Python without try-except and Catching KeyboardInterrupt in Python during program shutdown) which provided ways to do this, and also an effbot post.

Obviously this could cause problems if the catching code gets stuck, because you're left without that method of stopping program execution.

However, I was curious if this would be considered good programming practice?

0

There are 0 answers