Please offer some advice for this code. It all works, but I know that its messy and I don't think the Exception catching is doing what I want it to. Thanks in advance for any and all advice...
def main():
# loop over this forever
while True:
print '--- Getting next job for Device: %s' % device['Name']
# get a job from the db
try:
job = db.JobQ.find_one({'DeviceName':device['Name'],'Status':u'ToDo'})
except Exception as e:
print '!!! Error getting job for Device: %s' % device['Name']
if job:
# if there's a job, get all the other jobs for the same file
try:
job_list = [
j for j in db.JobQ.find(
{'Filename':job['Filename'],'Status':u'Todo'}
).sort('Created',ASCENDING)
]
except Exception as e:
print '!!! Error getting job list for Filename: %s' % job['Filename']
for job in job_list:
# mark the job 'InProgress'
job = db.JobQ.find_and_modify(
{'_id':ObjectId(job['_id'])},
{'$set':{
'Status':u'InProgress','Started':datetime.now()
}},new=True
)
print '--- Performing %s on %s' % (job['Type'], job['Filename'])
# try to do the job.. each job raises its own exceptions
try:
perform_job(job)
job['Status'] = u'Done'
job['Finished'] = datetime.now()
db.JobQ.save(job,safe=True)
except Exception as e:
# if any job fails, ditch the rest of the jobs and move on
print '!!! Error performing job: %s' % e
print 'Subsequent jobs for this filename will not run: %s'\
% job['Filename']
for job in job_list:
job['Finished'] = datetime.now()
job['Status'] = u'Failed'
db.JobQ.save(job,safe=True)
else:
print '--- No more jobs for Device: %s' % device['Name']
sleep(device['CycleTime'])
if __name__ == '__main__':
main()
try: perform_job(job)
.. this is the section I'm not sure about. Ifperform_job(job)
raises an Exception, the following 3 lines will not run, correct? Is this a normal way to do things? – MFB May 23 '12 at 13:37