Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.4, socket.error deprecated, new equivalent?

Originally the code was written like this:

except socket.error, err:
    print('Socket connection error... Waiting 10 seconds to retry.')
    del self.sock
    time.sleep(10)
    try_count += 1

The intention is to catch a socket connection error, this used to be err, or something similar.

However I have seen on a previous answer that socket.error has been deprecated from 2.6 onwards.

I can also confirm that 3.4 flags an error that says it does not support this syntax.

Does anyone please know the 3.4 equivalent?

like image 602
Savagefool Avatar asked Aug 12 '15 12:08

Savagefool


People also ask

How does Python handle socket exception?

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.

What is Setsockopt in Python?

The setsockopt() function provides an application program with the means to control socket behavior. An application program can use setsockopt() to allocate buffer space, control timeouts, or permit socket data broadcasts.

What is socket timeout Python?

Socket connection timeout High A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.

What is RECV in Python?

The recv method receives up to buffersize bytes from the socket. When no data is available, it blocks until at least one byte is available or until the remote end is closed. When the remote end is closed and all data is read, it returns an empty byte string.


2 Answers

Your issue is with the syntax, not socket.error:

This python 2 code is deprecated:

except Exception, e:

In favor of

except Exception as e:

So you want:

except socket.error as err:
like image 74
Eric Avatar answered Sep 19 '22 16:09

Eric


Indeed socket.error is deprecated in Python 3. You can now catch the superclass (OSError). And if want you can check within the except which kind of subclass of the exception was really raised (like ECONNREFUSED).

try:
    ...
except OSError as e:
    ...

See: https://docs.python.org/3/library/exceptions.html

like image 43
Melroy van den Berg Avatar answered Sep 19 '22 16:09

Melroy van den Berg