Non-blocking socket recvfrom

On page 19 of the Digi Python Programming Guide, the recvfrom method of the socket class takes an optional flag, “MSG_DONTWAIT to force a single socket transaction
to be non-blocking.” Without this flag, my test code - as expected - blocks until data arrives. With this flag set however, I see the following:
[pre]
Traceback (most recent call last):
File “”, line 65, in ?
File “”, line 36, in receive
socket.error: (11, ‘No more processes’)
[/pre]
If there is no data, shouldn’t I just expect socket.recvfrom(72, MSG_NOWAIT) to return None rather than generating an exception?

On a related note, if we are expected to trap this exception, shouldn’t something like the following work?
[pre]
try:
payload, src_addr = self.sd.recvfrom(72, MSG_DONTWAIT)
except socket.error:
pass ## handle error
[/pre]
I get …
[pre]
Traceback (most recent call last):
File “”, line 71, in ?
File “”, line 38, in receive
AttributeError: type object ‘_socketobject’ has no attribute ‘error’
[/pre]

Regarding your first comment. The exception error number 11 is the equivalent of EAGAIN. This is not made very clear by the way the error is raised. But this is expected if the call will not block. Typically when doing asynchronous I/O with nonblocking calls, you try to arrange to only call recvfrom when data is available, by using select or something. So that does make failing to have data an exception.

However, you are on the right approach here. You should be able to do ‘except socket.error’ if your initial import was ‘import socket’. My guess would be that you did a ‘from socket import *’ or similar. That will import the socket.error object into the main namespace simply as ‘error’. so ‘except error’ would be appropriate.

Keep in mind that you should probably have more than just a pass as part of the logic inside the except clause so that you can handle other socket.error instances cleanly as well.