From this question I tried following the answer by Maksim Skurydzin (3rd answer as of 2020-01-03 @ 6:33PM PST) but I get NameError: name 'timeout' is not defined
.
I'm trying to use TRY EXCEPT to catch a timeout when using sockets. I started with "Listing 11. Simple Python datagram echo server" from the IBM tutorial "Sockets programming in Python":
import socket
dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
dgramSock.bind( ('', 23000) )
while 1:
msg, (addr, port) = dgramSock.recvfrom( 100 )
dgramSock.sendto( msg, (addr, port) )
and I just added a few lines to get this:
import socket
from time import sleep
dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
dgramSock.bind(('', 62020))
dgramSock.setblocking(0)
while 1:
try:
msg, (addr, port) = dgramSock.recvfrom(64)
print msg
dgramSock.sendto(msg, (addr, port))
except timeout:
sleep(.001)
which gives the above error when I try to run it. This works the way I want it to when I change except timeout:
to except:
, but Python Docs discourages using except
this way (8.3. Handling Exceptions ..."The last except clause may omit the exception name(s), to serve as a wildcard. Use this with extreme caution, since it is easy to mask a real programming error in this way!"). In an effort to follow this advice, I found the answer (mentioned above) that seemed like a perfect fit and I thought I followed it correctly. What am I doing wrong?