I currently need to provide multiple keyboard interrupts for a program. Is there an easy way to do this with the signal class? I currently use the SIGINT/Ctrl+C but I can’t find any other keyboard mappings.
Would be nice to have more than 2 signals. How can I either define more signals or is there a better way to capture an “interrupt from a user”?
Here is a highlevel view of the current code:
def shutdown(signal, frame):
if(signal==2): #sigint
print 'do something'
elif signal==XX:
print 'do something else'
# continued...
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SOMEOTHERTYPE, shutdown)
print 'start'
t = Thread(target=run)
t.setDaemon(True)
t.start()
print 'Done, press ctrl c, or ctrl ? '
signal.pause()
The
Ctrl+\that has been mentioned is interpreted by your terminal software, and the key binding is configured throughstty. Unless you have some way of customizing your terminal software you’ll only be able to use the few signals that are already built in.Depending on how much functionality you need or how far you want to take it, another option is to write your own simple “process execution terminal”. This would be a script that executes an app for you and places your terminal in raw mode so that it can process keystrokes which perform custom actions.
Below is an oversimplified example showing what I mean. You could also do something similar via curses or urwid if you like.
To handle process output you’d need to capture the
stdout/stderrof and display it nicely to the screen, using ANSI escape sequences if you are manipulating the terminal manually, or using an urwid widget to display the output in a scrolling window, etc. The same idea would also extend to other GUI systems (wx, tkinter, etc) but terminal control was mentioned.Here is
term.pywhich implements a basic raw terminal interpreter:Here is a simple
target.pyscript to spin and print the signals it receives:Usage example: