2

I have a command line program that wants to pickle things when I send it a ctrl-C via the terminal. I have a some questions and concerns:

  1. How do I perform this handling? Do I check for a KeyboardInterrupt? Is there a way to implement an exit function?

  2. What if the program is halted in the middle of a write to a structure that I'm writing to? I presume these writes aren't treated atomically, so then how can I keep from writing trash into the pickle file?

2 Answers 2

3

You can use atexit for defining an exit handler. Modifications of Python objects will be treated atomically, so you should be fine as long as your code is arranged in a way that your objects are always in a consistent state between (byte code) instructions.

Sign up to request clarification or add additional context in comments.

2 Comments

Do I need to do anything in particular to ensure that?
Well, this really depends on your objects, the kind of operations you perform on them and what consistency means in your case. Hard to give general advice. Maybe post some code in another question?
1

(1) Use the atexit module:

def pickle_things(): pass import atexit atexit.register(pickle_things) 

(2) In general, you can't. Imagine someone trips on the power cord while your program is in the middle of a write. It's impossible to guarantee everything gets properly written in all cases.

However, in the KeyboardInterrupt case, the interpreter will make sure to finish whatever it's currently doing before raising that exception, so you should be fine.

2 Comments

The OP only asked about pressing Ctrl-C, not about any imaginable case :) Additionally, tripping on the power cord while the program is running would certainly keep him from writing trash into the pickle file...
@Sven, you're right, I was thinking about the general case :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.