为什么我不能在 raw_input 期间捕捉到 KeyboardInterrupt?

0xh*_*hes 5 python interrupt

这是一个测试用例。

try:
    targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
    print "Cancelled"
print targ
Run Code Online (Sandbox Code Playgroud)

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

NameError: name 'targ' is not defined
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

fal*_*tru 5

在上面的代码中,当引发异常时,targ 未定义。仅当未引发异常时才应打印。

try:
    targ = raw_input("Please enter target: ")
    print targ
except KeyboardInterrupt:
    print "Cancelled"
Run Code Online (Sandbox Code Playgroud)