0

One can send a KeyboardInterrupt to a running python program by pressing Ctrl-c. Is there a way to bind other keyboard combinations to custom python exceptions?

Specifically, I usually stop my program by pressing ctrl+c and then it handles the exception and exits cleanly. However, occasionally I want to stop it such that it performs a different cleanup procedure on exit. My program usually runs for several days without stopping so when I am launching it I do not know which way I want to use to kill it.

In a nutshell, I want to execute different cleanup procedures, based on some user input during runtime. My program is very computationally intensive so I would prefer a solution where I can send an exception rather than poll for user input.

niko
  • 1,128
  • 1
  • 11
  • 25
  • Possible duplicate of [Catching KeyboardInterrupt in Python during program shutdown](https://stackoverflow.com/questions/21120947/catching-keyboardinterrupt-in-python-during-program-shutdown) – Daniele Cappuccio May 03 '18 at 21:59
  • Is this Windows-only, *nix-only, or cross-plaftorm? On *nix, you can use a signal handler—`^C` sends a `SIGINT`, but if you want to send a different signal, you can open another terminal window, or just `^Z` your program into the background, and use the `kill` command to send a different signal instead.' – abarnert May 03 '18 at 22:04
  • Another option is to just run your whole program in a thread, or a child process, and let the main thread/process just wait on input and use that to decide what to do. – abarnert May 03 '18 at 22:07
  • Daniele, my question is different, I added some edits. – niko May 03 '18 at 22:10
  • abarnert, I am on unix and the kill command sounds like it might be able to do what I want. However, I am having difficulty finding how I can handle Ctrl+C and `kill` differently. – niko May 03 '18 at 22:11
  • Oh, I found it. Yes, this will do the trick, thanks. – niko May 03 '18 at 22:14

0 Answers0