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.
adds all the names without leading underscores (or only the names defined in the modules
__all__
attribute) infoo
into your current module.In the above code with
from socket import *
you just want to catchtimeout
as you've pulledtimeout
into your current namespace.from socket import *
pulls in the definitions of everything inside ofsocket
but doesn't addsocket
itself.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:
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:
Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.
When you do
from socket import *
python is loading asocket
module to the current namespace. Thus you can use module's members as if they are defined within your current python module.When you do
import socket
, a module is loaded in a separate namespace. When you are accessing its members, you should prefix them with a module name. For example, if you want to refer to asocket
class, you will need to writeclient_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
.As for the problem with timeout - all you need to do is to change
except socket.Timeouterror:
toexcept timeout:
, sincetimeout
class is defined insidesocket
module and you have imported all its members to your namespace.I had enough success just catchig
socket.timeout
andsocket.error
; although socket.error can be raised for lots of reasons. Be careful.Here is a solution I use in one of my project.
network_utils.telnet
Tests