how can I find it in python? thanks in advance
+7
A:
Try
import urllib
file = urllib.urlopen("http://stackoverflow.com/")
html = file.read()
and see if that works, or if it throws an exception. Even if you don't use the exact code, you should get the idea.
Vinay Sajip
2009-08-28 12:06:11
Lol, it only gives a false negative if SO is down ;-). Better check a couple of sites and assume connection if at least one is up.
Gamecat
2009-08-28 12:09:06
It was just an illustration - use any site you want!
Vinay Sajip
2009-08-28 12:15:41
it can also fail if a proxy server is running.
Nick D
2009-08-28 12:18:49
I think you mean "a proxy server is configured but not running".
Vinay Sajip
2009-08-28 12:21:11
Plenty of tricky failure modes. I know an environment that will popup a dialog box warning you that the connection attempt has been logged, and please enter username+password to connect to stackoverflow.com. That's a system-modal dialog I think.
MSalters
2009-08-28 15:29:02
+5
A:
If you have python2.6 you can set a timeout. Otherwise the connection might block for a long time.
try:
urllib2.urlopen("http://example.com", timeout=2)
except urllib2.URLError:
# There is no connection
Nadia Alramli
2009-08-28 12:11:23
+1 for the timeout. As Gamecat said, it could also mean that example.com is down :-)
Vinay Sajip
2009-08-28 12:17:15
@Vinay, that's right. Maybe he should try google.com. If google was down. Then I guess there is no internet ;)
Nadia Alramli
2009-08-28 12:19:59
you can set a timeout in 2.5 as well using import socket; socket.setdefaulttimeout(<time in seconds>);
tgray
2009-08-28 14:45:31