1

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()    
  • Can't reproduce. Probably something to do with how you run your program. Example of me running it: https://gist.github.com/anonymous/1439e9a79452feae7a65afec57eaf742 your csv-processing might be what isn't giving way, in which case you didn't post the relevant code. – jonatan Oct 11 '17 at 12:03
  • does your `product.verify` handle exceptions too? – ahmed Oct 11 '17 at 12:05
  • My first code example is from product.verify. I tried running with the try block in both the main and product.verify and got the same results. When I hit ctrl-c it exits out of the current row processing and goes to the next row but does not exit the entire program. – Roberta Fretz Oct 11 '17 at 13:14
  • Looks like something in `process the current row` is catching the KeyboardInterrupt exception. Like a bare `except`. – Julien Palard Oct 11 '17 at 14:10
  • I have now tried doing a bare except with a print and a raise in every method and in the main an except with a print and exit. When I run and do a ctrl-c I do not see any of my print statements and the processing of the current row is ended but execution continues at the next row. – Roberta Fretz Oct 11 '17 at 15:13
  • Have you tried opening a new terminal and running the program there? –  May 02 '20 at 18:00

1 Answers1

0

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)
Lifygen
  • 21
  • 4