-1

I have been looking on the web for about an hour searching for a command like Keyboardinterupt, but then for all keys. I need this for an try and Except loop which I want people to quit using any key. Is there another thing like KeyboardInterupt or do i need to become hackerman?

Thanks for your time

Stijn
  • 23
  • 7

1 Answers1

1

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.

mguijarr
  • 7,641
  • 6
  • 45
  • 72
  • Which is a lot of extra work to get around a "Press Ctrl+C to interrupt" message. Good answer though, as I misread the question. – TemporalWolf Apr 27 '17 at 19:39
  • Thanks a lot. Ill use the threading module then. Have a good day – Stijn Apr 27 '17 at 19:41
  • @Stijn according to a comment [here](http://stackoverflow.com/a/25442391/3579910) threading will not do what you want. – TemporalWolf Apr 27 '17 at 19:52
  • @TemporalWolf It is all using loops or threading, and a single loop wont let me continue doing something elsw while waiting for input. Thanks though. – Stijn Apr 27 '17 at 20:10