9

How to find out whether computer is connected to internet in python?

Oak Bytes
  • 4,649
  • 4
  • 36
  • 53

2 Answers2

16

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
  • 111,714
  • 37
  • 173
  • 152
7

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
  • 95,872
  • 14
  • 179
  • 191