Pressing ^C in a Python program. Also Progress Bar.
Archive - Originally posted on "The Horse's Mouth" - 2011-09-15 23:25:03 - Graham Ellis
If you want to stop a user interrupt via ^C aborting your program, you can catch a KeyboardInterrupt in Python. There's an example [here] which I wrote earlier today. It also shows how important it might be to use two try/except blocks rather than one - I've specified two inputs in the same block and, very irritatingly (and to make a point!) an entry of ^C to the second question knocks you back to the first question again for re-answering.
Once you disable ^C, you need to find some way of killing your process should an emergency need arise. Running on Unix / Linux systems from a command line, you can use ^Z to suspend the process and the use kill %!. You could also report the process number (via getpid (sample call [here]) to a .pid file, or to the user ...
... and another way to allow ^C to work in some circumstances is to look for it being pressed twice within a very short time - "double click"ed. There's a further example showing that [here]. That example also shows a progress bar in Python. Note ...
• use of \r rather than \n to send the cursor back but remain on the same line
• use of flush to ensure that output isn't buffered
• use of formatted fixed width output to ensure that each new report fully replaced previous one and doesn't leave spurious characters hen a short line replaces a longer one.