[Tutor] I need to ignore an error let the script continue to run
Jim
jf_byrnes at comcast.net
Tue May 5 16:28:05 EDT 2020
On 5/5/20 9:38 AM, Jim wrote:
> 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.
>
It seems every time I tried to test the return value from header I would
get an error, so I went the try/except route. This what I ended up with:
def parse_header(msg):
with open('/home/jfb/' + email_msg, 'rb') as fp:
header = BytesHeaderParser(policy=default).parse(fp)
# Now the header items can be accessed as a dictionary:
try:
username = header['to'].addresses[0].username + '\n'
except:
username = ' Blank \n'
try:
sender = header['to'].addresses[0].display_name + '\n'
except:
sender = ' Blank \n'
return ['To: ' + header['to']+'\n' ,
'From: ' + header['from']+'\n',
'Subject: ' + header['subject']+'\n',
'Return-Path: ' + header['return-path']+'\n' ,
#These do not exist in some headers'
'Recepient username: ' + username,
'Sender name: ' + sender,
]
This works when every thing is in the header and when the last two are
missing, so thanks for your help.
Regards, Jim
More information about the Tutor
mailing list