Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run atexit() when python process is killed

Tags:

I have a python process which runs in background, and I would like it to generate some output only when the script is terminated.

def handle_exit():     print('\nAll files saved in ' + directory)     generate_output()  atexit.register(handle_exit) 

Calling raising a KeyboardInterupt exception and sys.exit() calls handle_exit() properly, but if I were to do kill {PID} from the terminal it terminates the script without calling handle_exit().

Is there a way to terminate the process that is running in the background, and still have it run handle_exit() before terminating?

like image 894
Chan Jing Hong Avatar asked Nov 29 '16 13:11

Chan Jing Hong


2 Answers

Try signal.signal. It allows to catch any system signal:

import signal  def handle_exit():     print('\nAll files saved in ' + directory)     generate_output()  atexit.register(handle_exit) signal.signal(signal.SIGTERM, handle_exit) signal.signal(signal.SIGINT, handle_exit) 

Now you can kill {pid} and handle_exit will be executed.

like image 136
Gennady Kandaurov Avatar answered Oct 21 '22 06:10

Gennady Kandaurov


To enable signals when debugging PyCharm on Windows:

  1. Within PyCharm hit Ctrl + Shift + A to bring up the "Find Actions..." menu
  2. Search for "Registry" and hit enter
  3. Find the key kill.windows.processes.softly and enable it (you can start typing "kill" and it will search for the key)
  4. Restart PyCharm
like image 43
ChaimG Avatar answered Oct 21 '22 08:10

ChaimG