0
  1. What happens when a Python script that is running is killed (say using Ctrl+C) ?
  2. Suppose that during the execution of the script, I am dynamically storing some data. Now suppose that the script is suddenly killed. Is there a way to recognize that the process is getting killed and have Python save the data before the job is terminated ?
Paul
  • 26,170
  • 12
  • 85
  • 119
VanillaSpinIce
  • 263
  • 2
  • 10
  • 2
    Python developers mourn it. – Alicia Garcia-Raboso May 19 '17 at 00:07
  • For ctrl-c, take a look at http://stackoverflow.com/questions/8398845/what-is-the-difference-between-ctrl-c-and-sigint But that is not the only way a process can die and a process is not guaranteed any kind of notification before dying in certain cases. Which means it's up to you to periodically persist and checkpoint your data. – pvg May 19 '17 at 00:07
  • For a way to handle cleanup on your scripts exit, see this question http://stackoverflow.com/questions/17632759/performing-an-action-upon-unexpected-exit-python. Note however, like it says in one of the answers, if your script receives a `SIGKILL` signal you cannot perform any cleanup, and script will be forced to immediately terminate. – Christian Dean May 19 '17 at 00:10

1 Answers1

2
  1. Ctrl+C sends SIGINT, which can be trapped and handled or ignored.

The behavior of programs that are interrupted from the keyboard or other event is mediated by the operating system and so is not merely a python issue but would arise in C++, Java, JavaScript, etc. It can also differ somewhat between Linux/Unix and Windows. The usual default behavior is to stop the running process, and if there are complex storage or other procedures underway that should not be interrupted it is up to the programmer to set appropriate handlers or options with the OS. Even so, there are other mechanisms that can kill the process running the script. For example kill -9 or SIGKILL can not be trapped or handled.

  1. For handling Ctrl+C see for example Python: Catch Ctrl-C command. Prompt "really want to quit (y/n)", resume execution if no

This is not an instant solution to your needs, but could be simply modified, say to print "Do not use Control+C, instead wait for the program to finish and use the exit command".

There is a danger in running "save" functionality in response to an interrupt or signal that the process was already saving data when interrupted. Depending on how and where you save data, an issue of duplicates or corruption could arise.

Community
  • 1
  • 1
Paul
  • 26,170
  • 12
  • 85
  • 119