【问题标题】:Why can't I catch KeyboardInterrupt during raw_input?为什么我在 raw_input 期间无法捕获 KeyboardInterrupt?
【发布时间】:2013-08-09 15:05:43
【问题描述】:

这是一个测试用例。

try:
    targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
    print "Cancelled"
print targ

当我按ctrl+c-时我的输出如下

NameError: name 'targ' is not defined

我的意图是“取消”输出。当我尝试在 raw_input 期间捕获 KeyboardInterrupt 时,有什么想法会发生这种情况吗?

谢谢!

【问题讨论】:

    标签: python interrupt


    【解决方案1】:

    在上面的代码中,当引发异常时,没有定义 targ。只有在没有引发异常时才应该打印。

    try:
        targ = raw_input("Please enter target: ")
        print targ
    except KeyboardInterrupt:
        print "Cancelled"
    

    【讨论】:

      【解决方案2】:

      发生错误是因为如果引发 KeyboardInterrupt,则变量 targ 永远不会被初始化。

      try:
          targ = raw_input("Please enter target: ")
      except KeyboardInterrupt:
          print "Cancelled"
      
      Please enter target: 
      Cancelled
      
      >>> targ
      
      Traceback (most recent call last):
        File "<pyshell#19>", line 1, in <module>
          targ
      NameError: name 'targ' is not defined
      

      什么时候不发生,

      try:
          targ = raw_input("Please enter target: ")
      except KeyboardInterrupt:
          print "Cancelled"
      
      
      Please enter target: abc
      
      >>> targ
      'abc'
      

      如果未引发异常,您可以更改代码以打印 targ,方法是在 try 语句中打印它,请参阅以下演示。

      try:
          targ = raw_input("Please enter target: ")
          print targ
      except KeyboardInterrupt:
          print "Cancelled"
      
      
      Please enter target: abc
      abc
      
      try:
          targ = raw_input("Please enter target: ")
          print targ
      except KeyboardInterrupt:
          print "Cancelled"
      
      
      Please enter target: 
      Cancelled
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-16
        • 2018-03-14
        • 1970-01-01
        • 2019-05-27
        相关资源
        最近更新 更多