[Tutor] I need to ignore an error let the script continue to run
Alan Gauld
alan.gauld at yahoo.co.uk
Tue May 5 04:01:54 EDT 2020
On 05/05/2020 03:41, Jim wrote:
> It seems try/except will not process the keys after the missing one.
You need to wrap each bit that needs to continue in try/except.
Clunky I agree.
> 'Recepient username: ' + header['to'].addresses[0].username+'\n',
> 'Sender name: ' + header['from'].addresses[0].display_name
>
> They don't look like keys, but they do resolve to the info I want if it
> is in the header.
They aren't keys they are accessing attributes of some class that is
returned. You could check the return value from header first using an if
test. Or you could just wrap those two calls in their own try/except.
Or you could use get() and return a dummy instance of whatever class it
is with whatever default values you need.
So several solutions only you can decide which suits you best.
> def parse_header(msg):
> with open('/home/jfb/' + email_msg, 'rb') as fp:
> header = BytesParser(policy=default).parse(fp)
> # Now the header items can be accessed as a dictionary:
> try:
> headers = [> 'To: ' + header['to']+'\n' ,
Notice you access header['to'] here and print it directly.
> 'Recepient username: ' +
> header['to'].addresses[0].username+'\n',
But here you try to access attributes.
You can't have it both ways. Either its a printable string
or its an object with an addresses list...
If you do get a header with an object the first use is likely to break..
> msg_header = []
>
> for item in headers:
> msg_header.append(item)
This would be easier as a list comprehension:
msg_header = [item for item in headers]
But given its just a direct copy it would be easier still with
msg_header = headers[:]
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list