Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 docs 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? Can someone also explain the difference in the imports.

like image 799
Greg Brown Avatar asked Aug 08 '12 13:08

Greg Brown


People also ask

How does Python handle socket timeout?

As for the problem with timeout, all you need to do is to change except socket. Timeouterror: to except timeout: , since timeout class is defined inside socket module and you have imported all its members to your namespace.

How do you overcome timeout error in Python?

In Python, use the stdin. readline() and stdout. write() instead of input and print. Ensure that the input value to test cases is passed in the expected format.

How do I fix socket timeout exception?

Using try/catch/finally If you are a developer, so you can surround the socket connection part of your code in a try/catch/finally and handle the error in the catch. You might try connecting a second time, or try connecting to another possible socket, or simply exit the program cleanly.

How do you handle socket errors in Python?

If you do intend to handle each error in a different way, then you can leave them separate as you already have. But make sure to break / return at the end of the exception block so that you don't try the next. It's done that way in the socket examples, by using a continue in the loop.


2 Answers

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 doesn't add socket itself.

try:     # socketstuff except timeout:     print 'caught a timeout' 

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

For example, consider the following three python files:

# a.py def foo():     print "this is a's foo function"  # b.py def foo():     print "this is b's foo function"  # 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 

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

like image 190
stderr Avatar answered Sep 21 '22 09:09

stderr


I had enough success just catchig socket.timeout and socket.error; although socket.error can be raised for lots of reasons. Be careful.

import socket import logging  hostname='google.com' port=443  try:     sock = socket.create_connection((hostname, port), timeout=3)  except socket.timeout as err:     logging.error(err)  except socket.error as err:     logging.error(err) 
like image 38
ThorSummoner Avatar answered Sep 22 '22 09:09

ThorSummoner