4

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?

Community
  • 1
  • 1
RPiAwesomeness
  • 5,009
  • 10
  • 34
  • 52
  • 1
    You could catch it, clean up, then re-raise it. – wwii Jun 11 '15 at 19:42
  • @wwii That's a thought, interesting way of looking at it. – RPiAwesomeness Jun 11 '15 at 19:53
  • 2
    I would consider this a bad practice because it only prevents one of many ways for your file to get corrupted. If something else causes your server to die abruptly (power outage) you'd still have the same issue. I recommend making your file writes atomic by using a temp file. See this post: http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python – abaldwin99 Jun 12 '15 at 01:01

0 Answers0