开发者

How can I clean stuff up on program exit?

I have a command line program that w开发者_如何学Goants 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?


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.


(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜