Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I catch KeyboardInterrupt during raw_input?

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!

like image 517
0xhughes Avatar asked Aug 09 '13 15:08

0xhughes


1 Answers

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"
like image 140
falsetru Avatar answered Oct 20 '22 11:10

falsetru