Is there a way to run custom code on Jupyter shutdown?

I’m looking at implementing code carbon in my Jupyter notebooks. It’s a tool that tracks CO2 emissions from running code. Tracking emissions is relatively simple: you set up a tracker, run tracker.start() at the top of the notebook, and run tracker.end() at the end of the notebook.

Sometimes, however, I exit notebooks without running all cells, so I occasionally won’t run the tracker.stop() command that I need to log the emissions from that notebook session.

My hope is that there’s some way to define custom code that will be run when the kernel is shutdown. That way I make sure to call tracker.stop(). But I don’t know whether it’s possible to do this.

Yes, that is possible with the ipykernel which has do_shutdown method. I mainly use it to clean temporary files when shutting down a kernel.

3 Likes

Awesome, this is exactly what I was looking for. Thanks so much.

2 Likes

you should also be able to use atexit to ensure something is run when the process exits (cleanly).