There are a a couple of approaches to this. As some have commented you could used signal handling ... your [Ctrl]+[C] from the terminal where this is running in the foreground is dispatching a SIGHUP signal to your process (from the terminal's drivers).
Another approach would be to use a non-blocking os.read()
on sys.stdin.fileno
such that you're polling your keyboard one during every loop to see if an "exit" keystroke or sequence has been entered.
A similarly non-blocking polling approach can be implemented using the select
module's functionality. I've see that used with the termios
and tty
modules. (Seems inelegant that it needs all those to save, set changes to, and restore the terminal settings, and I've also seen some examples using os
and fcntl
; and I'm not sure when or why one would prefer one over the other if os.isatty(sys.stdin.fileno())
).
Yet another approach would be to use the curses
module with window.nodelay()
or window.timeout()
to set your desired input behavior and then either window.getch()
or window.getkey()
to poll for any input.