1

我希望我的程序在程序正在执行的终端窗口(具有焦点)中输入 ctrl-c 时停止执行。每个谷歌点击都告诉我这应该可以工作,但它没有。

首先,我尝试将 try 块放在我的 main 调用的类方法中:

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

然后我尝试将 try 块放在我的主程序中,但没有奏效:

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()    
4

1 回答 1

0

我最近(2020 年 5 月 2 日)使用 Anaconda2-Spyder(Python2.7)在 Windows-10 中遇到了同样的问题。我是使用 Spyder 的新手。通过尝试 stackoverflow 中列出的几个建议,我尝试了多种方法来让 [break] 或 [ctrl-c] 按预期工作。似乎没有任何效果。但是,我最终注意到的是程序在“KeyboardInterrupt”捕获后找到的行上停止。

【解决方案】:在调试器工具(菜单项或图标功能)中选择【运行当前行】或【继续执行】,程序的其余部分执行,程序正常退出。我构建了以下内容来试验键盘输入。

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)
于 2020-05-02T16:56:01.530 回答