Bug in socket module?

David M. Cooke cookedm+news at physics.mcmaster.ca
Wed Mar 31 05:55:36 CEST 2004

At some point, Koen  Vossen <koen_vossen at pandora.be> wrote:

> Hi, 
> I came across some exceptional behaviour (pun intended) when I was
> programming a small chat server. I've simplified my original code to the
> following minimal version that still exhibits the same problem:
> <code>
> #!/usr/bin/env python
> import socket
> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> s.bind(('', 1234))
> s.settimeout(10)
> try:
>     print "The Meaning of Life."
>     data, address = s.recvfrom(1024)
> except KeyboardInterrupt:
>     pass
> </code>
> When I start this little snippet, it just sits waiting for the socket to
> return some data, as expected. However, when I press CTRL-C before the
> timeout occurs it crashes on a KeyboardInterrupt exception, despite the
> fact that I have set up a handler to catch the latter.
> <output>
> koen at s031845:~/workdir> ./weird.py
> The Meaning of Life.
> Traceback (most recent call last):
>   File "./weird.py", line 11, in ?
>     data, address = s.recvfrom(1024)
> KeyboardInterrupt
> </output>
> When I omit the settimeout method call, or when I replace recvfrom by
> raw_input, the program behaves as expected.
> I'm using the following version of python:
> Python 2.3+ (#1, Jan  7 2004, 09:17:35)
> [GCC 3.3.1 (SuSE Linux)] on linux2
> I've found that on Windows the same behaviour occurs.
> Am I onto something here?

I think that's a bug. I looked at this and opened a bug report for you on
SourceForge (http://python.org/sf/926423). It's got my explanation of
what I think is going wrong.

There's a work around. This should work:

        data, address = s.recvfrom(1024)
    except KeyboardInterrupt:
        print 'not triggered'
except KeyboardInterrupt:
    print 'this should trigger'

So, put your error-handling code in the outermost try..except block.

|David M. Cooke

More information about the Python-list mailing list