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

Mats Wichmann mats at wichmann.us
Tue May 5 09:51:53 EDT 2020


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:

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?

>         #  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.



More information about the Tutor mailing list