[Tutor] I need to ignore an error let the script continue to run
Jim
jf_byrnes at comcast.net
Tue May 5 10:38:35 EDT 2020
On 5/5/20 3:01 AM, Alan Gauld via Tutor wrote:
> 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.
OK, thanks, I'll give them a try and see which on works 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..
When I started looking in to doing this I googled and one of the first
hits was the Python docs. This function was based on of the examples. It
did about 95% of what I wanted to do with out modification.
It looks that way but they actually return slightly different
information. I just ran it against a message with all the elements in
the header to verify it.
>
>> 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[:]
>
Thanks, I always have trouble understanding some of the more complex
list comprehension so I guess I don't even think about the simpler one
like this one. I completely forgot about [:].
Thanks, Jim
More information about the Tutor
mailing list