如何用Python检测计算机是否连接到互联网?

6

我有一个树莓派和一个WiFi dongle,所以标准的互联网LED灯不起作用。我尝试编写一个脚本,在树莓派有或没有互联网连接时切换LED灯。

目前我的代码如下:

#!/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

问题是不起作用。有人能告诉我如何检测我的树莓派是否有互联网并切换LED吗?


你根本不需要使用 loop_value。只需使用 while True 并在想要停止循环时使用 break。虽然这不是你的核心问题,但会使你的代码更易读。 - Martijn Pieters
哦,而且你真的想要修正你发布的缩进,因为它现在不符合 Python 的语法规范。 - Martijn Pieters
1个回答

8

已修正缩进。成功获取URL后中断。

#!/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

好的,你的脚本已经可以运行了,谢谢! - David Gölzhäuser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接