本文介绍了为什么在raw_input期间无法捕获KeyboardInterrupt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个测试用例.

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

当我按ctrl + c-

My output is as follows when I press ctrl+c-

NameError: name 'targ' is not defined

我的意图是将输出取消".有什么想法为什么当我尝试在raw_input期间捕获KeyboardInterrupt时会发生这种情况?

My intention is for the output to be "Cancelled". Any thoughts to as why this happens when I attempt to catch a KeyboardInterrupt during raw_input?

谢谢!

推荐答案

在上面的代码中,当引发异常时,未定义targ.您应该仅在未引发异常的情况下打印.

In above code, when exception raised, targ is not defined. You should print only when exception is not raised.

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

这篇关于为什么在raw_input期间无法捕获KeyboardInterrupt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 07:13