5

这是一个测试用例。

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

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

NameError: name 'targ' is not defined

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

谢谢!

4

2 回答 2

5

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

try:
    targ = raw_input("Please enter target: ")
    print targ
except KeyboardInterrupt:
    print "Cancelled"
于 2013-08-09T15:07:55.937 回答
2

发生错误是因为如果KeyboardInterrupt引发 a ,则变量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
于 2013-08-09T15:07:44.667 回答