Can not get keyboardInterrupt to catch ctrl c in python program running in linux

1.1k Views Asked by At

I want my program to stop executing when a ctrl-c is entered in the terminal window (that has focus) where the program is executing. Every google hit tells me this should work but it doesn't.

First I tried putting the try block in a class method my main invoked:

try:
  for row in csvInput:
     <process the current row...>
except KeyboardInterrupt:
  print '\nTerminating program!\n'
  exit()

and then I tried putting the try block in my main program and that didn't work:

if __name__ == '__main__':  
  try:  
    programArg = ProgramArgs(argparse.ArgumentParser) 
    args = programArg.processArgs()
    currentDir = os.getcwd()
    product = Product(currentDir, args.directory[0], programArg.outputDir) 
    product.verify()
  except KeyboardInterrupt:
    print '\nTerminating program!\n'
    exit()    
1

There are 1 best solutions below

0
On

I recently (May 2, 2020) hit this same issue in Windows-10 using Anaconda2-Spyder(Python2.7). I am new to using Spyder. I tried multiple ways to get [break] or [ctrl-c] to work as expected by trying several suggestions listed in stackoverflow. Nothing seemed to work. However, what I eventually noticed is that the program stops on the line found after the "KeyboardInterrupt" catch.

[Solution]: select [Run current line] or [continue execution] from the debugger tools (either menu item or icon functions) and the rest of the program executes and the program properly exits. I built the following to experiment with keyboard input.

def Test(a=0,b=0):
  #Simple program to test Try/Catch or in Python try/except.
  #[break] using [Ctrl-C] seemed to hang the machine.
  #Yes, upon [Ctrl-C] the program stopped accepting User # 
   Inputs but execution was still "hung".

   def Add(x,y):
       result = x+y
       return result

   def getValue(x,label="first"):
      while not x: 
        try:
            x=input("Enter {} value:".format(label))
            x = float(x)
            continue
        except KeyboardInterrupt:
            print("\n\nUser initiated [Break] detected." +
                  "Stopping Program now....")
            #use the following without <import sys>
            raise SystemExit   
            #otherwise, the following requires <import sys>
            #sys.exit("User Initiated [Break]!")
        except Exception:
            x=""
            print("Invalid entry, please retry using a " +
                  "numeric entry value (real or integer #)")
            continue
    return x

print ("I am an adding machine program.\n" +
       "Just feed me two numbers using "Test(x,y) format\n" +
       "to add x and y.  Invalid entries will cause a \n" + 
       "prompt for User entries from the keyboard.")       
if not a: 
    a = getValue(a,"first")
if not b:
    b = getValue(b,"second")        

return Add(a,b)