Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good way to detect when a Python program exits or crashes?

I have the following Python program running in a Docker container.

Basically, if the Python process exits gracefully (ex. when I manually stop the container) or if the Python process crashes (while inside some_other_module.do_work()) then I need to do some cleanup and ping my DB telling it that process has exited.

What's the best way to accomplish this? I saw one answer where they did a try catch on main(), but that seems a bit odd.

My code:

def main():
    some_other_module.do_work()

if __name__ == '__main__':
    main()
like image 310
farza Avatar asked Feb 19 '19 17:02

farza


2 Answers

I assume that the additional cleanup will be done by a different process, since the main process has likely crashed in a not recoverable way (I understood the question in this way).

The simplest way would be that the main process sets a flag somewhere (maybe creates a file in a specified location, or a column value in a database table; could also include the PID of the main process that sets the flag) when it starts and removes (or un-sets) that same flag if it finishes gracefully.

The cleanup process just needs to check the flag:

  • if the flag is set but the main process has ended already (the flag could contain the PID of the main process, so the cleanup process uses that to find if the main process is still running or not), then a cleanup is in order.
  • if the flag is set and the main process is running, then nothing is to be done.
  • if the flag is not set, then nothing is to be done.
like image 92
Ralf Avatar answered Nov 15 '22 11:11

Ralf


Try-catch on main seems simplest, but doesn't/may not work for most things (please see comments below). You can always except specific exceptions:

def main():
    some_other_module.do_work()

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        if e == "<INSERT GRACEFUL INTERRUPT HERE>":
            # finished gracefully
        else:
            print(e)
            # crash
like image 39
PrinceOfCreation Avatar answered Nov 15 '22 10:11

PrinceOfCreation