【问题标题】:Can not get keyboardInterrupt to catch ctrl c in python program running in linux在linux中运行的python程序中无法获取keyboardInterrupt来捕获ctrl c
【发布时间】:2018-03-23 02:14:20
【问题描述】:

当在程序正在执行的终端窗口(具有焦点)中输入 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()    

【问题讨论】:

  • 无法复制。可能与您运行程序的方式有关。我运行它的示例:gist.github.com/anonymous/1439e9a79452feae7a65afec57eaf742 您的 csv-processing 可能没有让位,在这种情况下您没有发布相关代码。
  • 你的product.verify也处理异常吗?
  • 我的第一个代码示例来自 product.verify。我尝试在 main 和 product.verify 中使用 try 块运行并得到相同的结果。当我按 ctrl-c 时,它退出当前行处理并进入下一行,但不退出整个程序。
  • 看起来process the current row 中的某些东西正在捕获 KeyboardInterrupt 异常。就像一个裸露的except
  • 我现在已经尝试在每个方法中使用 print 和 raise 做一个裸 except,主要是使用 print 和 exit。当我运行并执行 ctrl-c 时,我看不到任何打印语句,并且当前行的处理已结束,但在下一行继续执行。

标签: python linux keyboardinterrupt control-c


【解决方案1】:

我最近(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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 2022-08-03
    • 2020-03-15
    相关资源
    最近更新 更多