Why can't I catch KeyboardInterrupt during raw_input?

与世无争的帅哥 提交于 2019-12-12 14:23:33

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!