[Tutor] finally without try or except

Tino Dai oberoc at gmail.com
Mon Jul 30 21:20:06 CEST 2012


On Mon, Jul 30, 2012 at 1:44 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote:

> > Actually, what I'm doing is keeping a pending item log in memory as an
> array
> > and then saving it to the DB at the end of the program, but what happens
> if
> > the user hits ctrl-c, then the pending items array is lost. That's the
> use
> > case that I'm looking for a solution to.
>
> http://docs.python.org/library/exceptions.html#exceptions.KeyboardInterrupt
>
> Ctrl-c generates a KeyboardInterrupt exception which you can catch with a
> try-except clause. Of course, if the user hits ctrl-c again while
> executing the "except" portion of the python code, it will generate another
> exception. The second exception will not be caught without another explicit
> try-except clause and ad infinitum for the third press of ctrl-c.
>

Yes, but that would involve surrounding the entire method with a try except
finally block. I was
told by the Python-Guru-In Residence that shouldn't emulate Java code in
Python, and that was
generally bad programming practice (no flame war intended)

>
> You probably want to rethink your process. You can write the item log
> to the db in the except clause but this can be buggy as a second ctrl-c
> will stop it.


I want to do this in the finally block to insure that the records would be
written out to the
DB, hence my original question

Often users will repeatedly hit ctrl-c until the program
> stops. Alternatively, you can store the item log in the db and update it
> as the program progresses.


This is how the program was originally structured, but we found performance
problems with in.
It's using Django and an Oracle DB, which is notoriously bad for single
record read/writes. So, I
figured why don't we append them all to an array, and write them out at the
end of the program.


> This will be the most robust as it will
> also work for cases where the program is terminated without the use of
> the keyboard (i.e. kill -9, task manager, computer reboot, etc.)  but
> it might also slow the program down. You could also try writing the
> item log to a local file using pickle or csv.
>
>  -Thanks,
Tino
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120730/b6230f76/attachment.html>


More information about the Tutor mailing list