Subject: [Tutor] Re: Tutor Testing for response from a Web site
Thu Apr 10 03:49:28 2003


I'm keeping this on the list where the real gurus are as there rarely to be 
found here ;-) Okay, MAL is coming round today but that's mere coincidence!

On 2003-04-10 at 06:11:35 [+0200], you wrote:
> Charlie:
> Thanks for responding.
> I just wanted to know how to test for a connection that cannot for one 
> reason or another, be made with a server.
> >From your response, I checked into the "IOError." I am not sure
> about how to use these, but from some examples in some Python books I 
> have, here are some questions I hope you can answer for me:
> 1)  Is the following code ok now in order to catch the no connection
>      possibility?
> 2)  After the IOError exception, I also included another exception that
>      as you said, catches every possible error. Is this correct too the 
>      way I coded this after the other exception?

well, you don't need to print "unknown error" you can actually get all the 
information from the traceback. Try print sys.exc_info() instead. I still 
don't see the need to carry on execution with other errors as your script 
probably isn't doing what you want.

> 3)  Can this code be written so that I only need to have ONE
>      f_object.close() statement if any exception occurs? As it stands 
>      now, I have to repeat it for each exception.
Yes, you just add a finally: f_object.close() at the end.

> 4)  Is there some built in time limit, say one minute, in which Python
>      tries to connect to a server before giving up and calling the 
>      exception? If so, can one regulate how long Python waits before 
>      giving up and calling the exception, and can one regulate how many 
>      times Python tries to connect? I could put things in a loop to do 
>      that I guess.

Yes, I think urllib.urlopen() has a two minute timeout. You might be able 
to set this yourself. This is from the docs for urlilib2:

urlopen(url, data=None) -- basic usage is that same as original urllib.  
pass the url and optionally data to post to an HTTP URL, and get a 
file-like object back.  One difference is that you can also pass a Request 
instance instead of URL.  Raises a URLError (subclass of IOError); for HTTP 
errors, raises an HTTPError, which can also be treated as a valid response.

This basically means you can get more useful error messages.

import urllib, sys

metURL = "" 
# f_object = open("c:\\python_pgms\\plot_guidance\\met_data.txt", 'w')
f_object = open("c:/python_pgms/plot_guidance/met_data.txt", "w")
# this is easier to read and more portable
# this is Python so we don't need more \n than absolutely necessary
   metall = urllib.urlopen(metURL).read()
except IOError:
   print "Server connection could not be made."
	print "Something has gone wrong"
    print sys.exc_info()

>Thanks much for your help!
> Henry Steigerwaldt
> Hermitage, TN
> Email: