Skip to content
Advertisement

Handling a timeout error in Python sockets

I am trying to figure out how to use the try and except to handle a socket timeout.

from socket import *

def main():
    client_socket = socket(AF_INET,SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message',(server_host,server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.Timeouterror:
            # More code

The way I added the socket module was to import everything, but how do I handle exceptions?

In the documentation it says you can use socket.timeouterror, but that doesn’t work for me. Also, how would I write the try exception block if I did import socket? What is the difference in the imports?

Advertisement

Answer

from foo import *

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import *, you just want to catch timeout as you’ve pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket, but it doesn’t add socket itself.

try:
    # Socket stuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in two or more modules that are imported in this way will clobber one another.

For example, consider the following three Python files:

# File "a.py"
def foo():
    print "this is a's foo function"

# File "b.py"
def foo():
    print "this is b's foo function"

# File "yourcode.py"
from a import *
from b import *
foo()

If you run yourcode.py, you’ll see just the output “this is b’s foo function”.

For this reason I’d suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            # More code

It is just a tiny bit more typing, but everything’s explicit and it’s pretty obvious to the reader where everything comes from.

Advertisement