2
votes

I have a bit of python code to to try and make raw_input catch keyboard interrupts. If I run the code in this function it works perfectly fine. But if I run it in my program, the print statement is never made, indicating that the keyboard interrupt is not caught. The program attempts to exit and fails until it escalates to SIGKILL, which of course works fine. My guess is somewhere else the keyboard interrupt is being caught, preventing the exception from running at all. My question is, where would such an interrupt likely occur, and how can I prevent it from blocking this one. My plan has been to add a slight delay between the program catching a keyboard interrupt and killing itself to give excepting here a moment to catch.

Any ideas appreciated

Thanks!

import sys
def interruptable_input(text=''):
  '''Takes raw input, but accepts keyboard interrupt'''
  try:
    return raw_input(text)
  except KeyboardInterrupt:
    print "Interrupted by user"
    sys.exit()
2
Simply calling this function from within a 2.7.10 interactive interpreter session and then hitting CTRL+C correctly prints the "Interrupted by user" and exits for me. I can't reproduce what you mean... - Byte Commander

2 Answers

2
votes

I have narrowed it down to the following:

import sys
text=''
try:
    print raw_input(text)
except KeyboardInterrupt:
    print "Interrupted by user"
    sys.exit()

Which works perfectly when i run it on the command line using python 2.7. It lets me type an input on the console and when I hit ctrl+c it prints intterupted by user

Edit: I misread your question at first, however when i use the method from your example and call it from another method the result is the same

2
votes

I have determined the reason for my issue was another interrupt handler killing the script before the KeyboardInterrupt was hit. I solved it by setting my own interrupt handler for signal.SIGINT like so:

import sys
import signal
signal.signal(signal.SIGINT, signal_term_handler)
def signal_term_handler(signal, frame):
  '''Handles KeyboardInterrupts to ensure smooth exit'''
  rospy.logerr('User Keyboard interrupt')
  sys.exit(0)

it's slightly less direct but it get's the job done. Now raw_input() will simply die when told to.