KeyboardInterrupt
is an exception raised when Python catches the SIGINT
system signal. You can raise it yourself at will: raise KeyboardInterrupt
. However, you cannot generate the SIGINT signal yourself, the signal has to be sent to the process. A similar effect is achieved by pressing CTRL-C, which emits the SIGINT signal to the running process.
If you have a loop and want to break it on a key, you have to listen for any keyboard event and raise an exception when it is caught; you need a mechanism to execute your code and listening for events at the same time.
I can imagine something like this:
- you start a Python subprocess with your code
- you enter a loop, catching any keyboard keypress
- when you get the keypress event you send the SIGINT signal to the other process
Example, Python 2.7 (not tested):
import multiprocessing
import time
import signal
import select
import sys
import os
def my_code():
while True:
print 'Do something...'
time.sleep(1)
if __name__ == '__main__':
p = multiprocessing.Process(target=my_code)
p.start()
# wait for a key
select.select([sys.stdin],[],[])
os.kill(p.pid, signal.SIGINT)
Due to stdin buffering, on Linux at least, the code above requires [Enter] after key is pressed.
However, it can be worked-around easily using some Python module like getc
for example.