Rorschach Rorschach - 6 months ago 12
Python Question

how to close python script without just activating "except" in try/except statement

I have a python script running over some 50,000 items in a database, it takes about 10 seconds per item and I want to stop it.

But, if i just press ctrl + C while the code is in the try except part, then my program enter the expect statement and delete that item then continue. The only way to close the program is to repeatedly delete items this way until I, just be sheer luck, catch it not in the try statement.

How do I exit the script without just killing a try statement?

EDIT 1

I have a statement that looks something like this:

for item in items:
try:
if is_item_gone(content) == 1:
data = (item['id'])
db.update('UPDATE items SET empty = 0 WHERE id = (%s);', data)
else:
do alot of stuff
except:
data = (item['id'])
db.delete('...')


EDIT 2

The top of my connect to db code looks like:

#!/usr/bin/python
import MySQLdb
import sys

class Database:
....

Answer

The issue is because you are using a blanket except which is always a bad idea, if you catch specific exceptions then when you KeyboardInterrupt your script will stop:

for item in items:
   try:
      if is_item_gone(content) == 1:
         data = (item['id'])
         db.update('UPDATE items SET empty = 0 WHERE id = (%s);', data)
      else:
          do alot of stuff
   except MySQLdb.Error  as e:
      print(e)
      data = (item['id'])
      db.delete('...')

If you have other exceptions to catch you can use multiple in the except:

 except (KeyError, MySQLdb.Error) as e

At the very least you could catch Exception as e and print the error.

for item in items:
   try:
      if is_item_gone(content) == 1:
         data = (item['id'])
         db.update('UPDATE items SET empty = 0 WHERE id = (%s);', data)
      else:
          do alot of stuff
   except Exception as e:
      print(e)
      data = (item['id'])
      db.delete('...')

The moral of the story is don't use a blanket except, catch what you expect and logging the errors might also be a good idea.

Comments