Catching control-C
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Tue Jul 7 01:07:08 EDT 2009
On Mon, 06 Jul 2009 15:02:26 -0700, Michael Mossey wrote:
> On Jul 6, 2:47 pm, Philip Semanchuk <phi... at semanchuk.com> wrote:
>> On Jul 6, 2009, at 5:37 PM, Michael Mossey wrote:
>>
>> > What is required in a python program to make sure it catches a
>> > control-
>> > c on the command-line? Do some i/o? The OS here is Linux.
>>
>> You can use a try/except to catch a KeyboardInterrupt exception, or you
>> can trap it using the signal
>> module:http://docs.python.org/library/signal.html
>>
>> You want to trap SIGINT.
>>
>> HTH
>> Philip
>
> Thanks to both of you. However, my question is also about whether I need
> to be doing i/o or some similar operation for my program to notice in
> any shape or form that Control-C has been pressed. In the past, I've
> written Python programs that go about their business ignoring Ctrl-C.
I bet that somewhere in your code you have something like:
for x in really_big_list:
try:
long_running_process(x)
except:
continue
If that's what you're doing, stop! The correct way is:
for x in really_big_list:
try:
long_running_process(x)
except Exception:
# Let KeyboardInterrupt and SystemExit through.
continue
or even:
for x in really_big_list:
try:
long_running_process(x)
except (KeyboardInterrupt, SystemExit):
print "User requested exit... shutting down now"
cleanup()
raise
except Exception:
continue
--
Steven
More information about the Python-list
mailing list