[Tutor] finally without try or except
Prasad, Ramit
ramit.prasad at jpmorgan.com
Mon Jul 30 19:44:54 CEST 2012
> 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.
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. 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 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.
Ramit
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list