1

This seems to be the code for the poplib.error_proto.

class error_proto(Exception): pass

It just passes the bytes from the POP response in the exception. What I would like to do is catch any exception, take those bytes, use .decode('ascii') on them, and print them as a string. I've written my own test setup like so:

class B(Exception): pass

def bex(): raise B(b'Problem')

try:
    bex()
except B as err:
    print(err.decode('ascii'))

I've tried replacing the last line with:

    b = bytes(err)
    print(b.decode('ascii'))

But to no avail. Is this possible and if so, how would I implement this?

UPDATE: Though, as falsetru points out, the documentation says results are returned as strings, this is not the case:

>>> p = poplib.POP3('mail.site.com')
>>> p.user('[email protected]')
b'+OK '
>>> p.pass_('badpassword')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python33\lib\poplib.py", line 201, in pass_
    return self._shortcmd('PASS %s' % pswd)
  File "C:\Python33\lib\poplib.py", line 164, in _shortcmd
    return self._getresp()
  File "C:\Python33\lib\poplib.py", line 140, in _getresp
    raise error_proto(resp)
poplib.error_proto: b'-ERR authorization failed  Check your server settings.'
>>>

1 Answer 1

2

According to poplib.error_proto documentation:

Exception raised on any errors from this module (errors from socket module are not caught). The reason for the exception is passed to the constructor as a string.

So, you don't need to decode it.


UPDATE It seems like the documentation does not match the actual implementation.

You can access the arguments passed to the exception constructor using args attribute.

p = poplib.POP3('mail.site.com')
try:
    p.user('[email protected]')
    p.pass_('badpassword')
except poplib.error_proto as e:
    print(e.args[0].decode('ascii')) # `'ascii'` is not necessary.
3
  • Please see my update, doesn't the b prefix mean it is bytes()?
    – Sean
    Dec 13, 2013 at 15:17
  • Thank you very much, this is precisely what I was looking for. And I always saw decode('utf-8'), so I figured 'ascii' was required for ASCII. That's a two-fer!
    – Sean
    Dec 13, 2013 at 15:40
  • 1
    @Sean, utf-8 encoding is designed to be backward compatible with ascii encoding. And encoding parameter of bytes.decode defaults to utf-8; You can omit it. :)
    – falsetru
    Dec 13, 2013 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.