Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if Computer is contacted to the internet with Python? [duplicate]

I have a Raspberry Pi with a WiFi dongle, so the standard internet LEDs don't work. I tried to write a script that toggles an LED whether the Pi have internet or not.

This is what I have for now:

#!/usr/bin/python
import urllib2 
import time, os

os.system("gpio mode 6 out && gpio mode 5 out")

loop_value = 1

while (loop_value == 1):
    try:
        urllib2.urlopen("http://www.google.com")
    except urllib2.URLError, e:
        time.sleep( 1 )
        print "Not Connected"
        os.system("gpio write 6 0 && gpio write 5 1")
    else:
       print "Connected"
       os.system("gpio write 6 1 && gpio write 5 0")
       loop_value = 1

The problem is that is isn't working. can someone tell me how I can detect it my pi has internet or not and then print toggle the LEDs?

like image 867
David Gölzhäuser Avatar asked Jun 25 '13 17:06

David Gölzhäuser


1 Answers

Fixed indentation. break on successful url fetch.

#!/usr/bin/python
import os
import time
import urllib2 

os.system("gpio mode 6 out && gpio mode 5 out")

while True:
    try:
        urllib2.urlopen("http://www.google.com").close()
    except urllib2.URLError:
        print "Not Connected"
        os.system("gpio write 6 0 && gpio write 5 1")
        time.sleep(1)
    else:
        print "Connected"
        os.system("gpio write 6 1 && gpio write 5 0")
        break
like image 109
falsetru Avatar answered Nov 14 '22 22:11

falsetru