这是一个测试用例。
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
print targ
当我按下ctrl+c时,我的输出如下所示-
NameError: name 'targ' is not defined
我的意图是输出“已取消”。当我尝试在输入时捕获KeyboardInterrupt时,为什么会发生这种情况?
谢谢!
try:
targ = raw_input("Please enter target: ")
print targ
except KeyboardInterrupt:
print "Cancelled"
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'
try
语句中打印targ
,以确保没有异常抛出时进行打印。请参考以下演示进行操作。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