[Tutor] I need to ignore an error let the script continue to run

Jim jf_byrnes at comcast.net
Tue May 5 10:47:27 EDT 2020


On 5/5/20 8:51 AM, Mats Wichmann wrote:
> On 5/4/20 8:41 PM, Jim wrote:
>> I ended up writing the program that lets me view parts of an email
>> header in a pop up window without opening the message. It worked great
>> until I received an email with a header that did not contain all the
>> items I was trying to retrieve.
>>
>> The parse_header function processes the data and passes it on to another
>> part of the script to display it. In the header I am working with there
>> is no 'Recepient username' in the header.I need a way to ignore any
>> missing keys and process the ones that are there.
>>
>> It seems try/except will not process the keys after the missing one.
>>
>> I looked at something like dict.get(key, 'blank') but I can't figure out
>> how to handle these two cases:
>>
>> 'Recepient username: ' + header['to'].addresses[0].username+'\n',
>> 'Sender name: ' + header['from'].addresses[0].display_name
> 
> I believe these are wired to work so you can do "in" checks:

OK, I'll give that a try.

> if 'Recipient username' in header:
>      # do something with the field
> 
>>          header = BytesParser(policy=default).parse(fp)
> 
> is there a reason you don't use BytesHeaderParser, since your area of
> interest is the headers?

Yes, I got this from the Python docs and their example did almost 
exactly what I wanted to do. I was so happy it worked I didn't look 
closer at it to realize I was grabbing unnecessary info. Thanks for 
pointing that out.

>>          #  Now the header items can be accessed as a dictionary:
>>      try:
>>          headers = ['To: ' + header['to']+'\n' ,
>>          'From: ' + header['from']+'\n',
>>          'Subject: ' + header['subject']+'\n',
>>          'Return-Path: ' + header['return-path']+'\n' ,
>>          #This does not exist in some headers
>>          'Recepient username: ' + header['to'].addresses[0].username+'\n',
>>          'Sender name: ' + header['from'].addresses[0].display_name
>>          ]
>>          msg_header = []
>>
>>          for item in headers:
>>              msg_header.append(item)
> 
> this seems a complete waste: you've made a list, and then you loop over
> the list and append its elements to a new list.

In it's present form it is. Originally I just hard coded the list and 
returned it. Then I had the error with the missing element and was 
playing around with it trying to find a way to handle the error. I was 
thinking if I built the list item by item maybe I could check for errors 
and handle them somehow. So far I haven't been successful, but now I 
have some more things to try.

Thanks,  Jim

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 




More information about the Tutor mailing list