views:

218

answers:

2

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
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
It was just an illustration - use any site you want!
Vinay Sajip
it can also fail if a proxy server is running.
Nick D
I think you mean "a proxy server is configured but not running".
Vinay Sajip
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
+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
+1 for the timeout. As Gamecat said, it could also mean that example.com is down :-)
Vinay Sajip
@Vinay, that's right. Maybe he should try google.com. If google was down. Then I guess there is no internet ;)
Nadia Alramli
you can set a timeout in 2.5 as well using import socket; socket.setdefaulttimeout(<time in seconds>);
tgray
@tgray, great tip! thanks.
Nadia Alramli