Capturing a python application before it exits

I have a python application that should be very durable, but sometimes the process just disappears and I don't know why. When this happens, nothing is logged, so I’ll lose a little.

Is there any way in the code that I can hook into the exit event, or in some other way get some code to run before the process finishes? I would like to record the state of memory structures in order to better understand what is happening.

+7
python crash
source share
3 answers

atexit pronounced "exit". The first time I read this function name, I read it as "texit", which makes almost no sense.

+8
source share

You can try to run the application directly from the console (cmd on windows, sh / bash / etc on unix) so that you can see any stack trace, etc. printed on the console when the process dies.

+3
source share

I'm not sure you can change the source code, but if possible, you can try:

 def debugexcept(type, value, tb): if hasattr(sys, 'ps1') or not (sys.stderr.isatty() and sys.stdin.isatty()) or type == SyntaxError: sys.__excepthook__(type, value, tb) else: import traceback, pdb traceback.print_exception(type, value, tb) print pdb.pm() sys.excepthook = debugexcept 

If you run your python program from the command line, you should be flushed to the python debugger when it dies, assuming something "bad" happened, throws an exception. I assume that stderr / stdout were captured and you do not see any exception?

those. look for something like:

 sys.stdout = open('stdout.log', 'w') sys.stderr = open('stderr.log', 'w') 

If a process dies without any exception, it can be harder to find. One (very difficult way) in the windows will use something like windbg to join the process and set a breakpoint in the CRT in some appropriate place.

Good luck

+3
source share

All Articles