Performing an action upon unexpected exit python

旧城冷巷雨未停 提交于 2019-12-04 20:38:14

Your atexit usage is wrong. It expects a function and its arguments, but you're just calling your function right away and passing the result to atexit.register(). Try:

atexit.register(saveFile, list)

Be aware that this uses the list reference as it exists at the time you call atexit.register(), so if you assign to list afterwards, those changes will not be picked up. Modifying the list itself without reassigning should be fine, though.

You could use the handle_exit context manager from this ActiveState recipe:

http://code.activestate.com/recipes/577997-handle-exit-context-manager/

It handles SystemExit, KeyboardInterrupt, SIGINT, and SIGTERM, with a simple interface:

def cleanup():
    print 'do some cleanup here'

def main():
    print 'do something'

if __name__ == '__main__':
    with handle_exit(cleanup):
        main()

There's nothing you can in reaction to a SIGKILL. It kills your process immediately, without any allowed cleanup.

Catch the SystemExit exception at the top of your application, then rethrow it.

There are a a couple of approaches to this. As some have commented you could used signal handling ... your [Ctrl]+[C] from the terminal where this is running in the foreground is dispatching a SIGHUP signal to your process (from the terminal's drivers).

Another approach would be to use a non-blocking os.read() on sys.stdin.fileno such that you're polling your keyboard one during every loop to see if an "exit" keystroke or sequence has been entered.

A similarly non-blocking polling approach can be implemented using the select module's functionality. I've see that used with the termios and tty modules. (Seems inelegant that it needs all those to save, set changes to, and restore the terminal settings, and I've also seen some examples using os and fcntl; and I'm not sure when or why one would prefer one over the other if os.isatty(sys.stdin.fileno())).

Yet another approach would be to use the curses module with window.nodelay() or window.timeout() to set your desired input behavior and then either window.getch() or window.getkey() to poll for any input.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!