问题
here is a test case.
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
print targ
My output is as follows when I press ctrl+c-
NameError: name 'targ' is not defined
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?
Thanks!
回答1:
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"
回答2:
The error occurs because if a KeyboardInterrupt is raised, the variable targ never gets initialised.
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
When, it does not occur,
try:
targ = raw_input("Please enter target: ")
except KeyboardInterrupt:
print "Cancelled"
Please enter target: abc
>>> targ
'abc'
You could change your code to print targ if an exception is not raised, by printing it in the try statement, see the following demo.
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
来源:https://stackoverflow.com/questions/18149870/why-cant-i-catch-keyboardinterrupt-during-raw-input