0

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?

TRS-80
  • 1
  • 2
  • The code you copied from presumably included a line like `from socket import timeout` to actually bring in the definition of this name. – jasonharper Jan 04 '21 at 04:13
  • It already has `import socket`, doesn't that already cover `from socket import timeout`? – TRS-80 Jan 04 '21 at 05:33
  • @TRS-80: *"It already has `import socket`, doesn't that already cover `from socket import timeout`?"* - With just `import socket` you would need to use `socket.timeout` instead of just `timeout`. – Steffen Ullrich Jan 04 '21 at 07:57

0 Answers0