Any way to turn off exception handling? (debugging)

Vinay Sajip vinay_sajip at yahoo.co.uk
Fri Feb 12 05:42:07 EST 2010


On Feb 11, 7:12 pm, mk <mrk... at gmail.com> wrote:
> Peter Otten wrote:
> > try:
> >    ...
> > except socket.error:
> >    ...
>
> > #untested
> > import socket
>
> > class SocketWrapper:
> >     def __getattr__(self, name):
> >         return getattr(socket, name)
> >     error = None
>
> > import module_using_socket
> > module_using_socket.socket = SocketWrapper()
>
> Very interesting solution. Thanks!
>
> Regards,
> mk

On Feb 11, 2:12 pm, mk <mrk... at gmail.com> wrote:
> Peter Otten wrote:
> > try:
> >    ...
> > except socket.error:
> >    ...
>
> > #untested
> > import socket
>
> > class SocketWrapper:
> >     def __getattr__(self, name):
> >         return getattr(socket, name)
> >     error = None
>
> > import module_using_socket
> > module_using_socket.socket = SocketWrapper()
>
> Very interesting solution. Thanks!
>
> Regards,
> mk

You could refine Peter's suggestion further. For example, if you don't
want to change the flow of execution (as Peter's suggestion does) but
just log the occurrences, then you could try something like this:

# socktest.py

import socket

def test():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect(('localhost', 9999))
    except socket.error, e:
        print '-- handler printing:', e

# sockwrap.py

import socket
import traceback
import logging

class SocketWrapper:
    def __getattr__(self, name):
        return getattr(socket, name)

    @property
    def error(self):
        # In practice you could log to a specific logger
        logging.exception('A socket error occurred')
        return getattr(socket, 'error')

def wrap(mod):
    mod.socket = SocketWrapper()

# Now try it out

>>> import socktest, sockwrap
>>> sockwrap.wrap(socktest)
>>> socktest.test()
ERROR:root:A socket error occurred
Traceback (most recent call last):
  File "socktest.py", line 7, in test
    s.connect(('localhost', 9999))
  File "<string>", line 1, in connect
error: (10061, 'Connection refused')
-- handler printing: (10061, 'Connection refused')
>>>

Regards,

Vinay Sajip



More information about the Python-list mailing list