Python检查互联网连接与树莓派的合作
我正在为我的家建立一个安全摄像机系统,其中包括一些树莓派。每个摄像头系统的其中一项功能是显示互联网连接的亮点。为此,我使用了python check to see if host is connected to network找到的代码并将其修改为。Python检查互联网连接与树莓派的合作
#! /usr/bin/python
import socket
import fcntl
import struct
import RPi.GPIO as GPIO
import time
pinNum = 8
GPIO.setmode(GPIO.BCM) #numbering scheme that corresponds to breakout board and pin layout
GPIO.setup(pinNum,GPIO.OUT) #replace pinNum with whatever pin you used, this sets up that pin as an output
#set LED to flash forever
def check_connection():
ifaces = ['eth0','wlan0']
connected = []
i = 0
for ifname in ifaces:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
connected.append(ifname)
print "%s is connected" % ifname
while True:
GPIO.output(pinNum,GPIO.HIGH)
time.sleep(0.5)
GPIO.output(pinNum,GPIO.LOW)
time.sleep(0.5)
GPIO.output(pinNum,GPIO.LOW)
time.sleep(2.0)
except:
print "%s is not connected" % ifname
i += 1
return connected
connected_ifaces = check_connection()
然而,当我通过我的皮运行代码的错误读取:
[email protected] ~/Desktop $ while True:
> ^
> TabError: inconsistent use of tabs and spaces in indentation
> ^C
任何人都知道这个问题?道歉,如果它是一个基本的,我是Python编程的新手。总之,我希望当有互联网连接时,引脚8上的指示灯将亮起。
谢谢!
Python对缩进非常挑剔,因为它使用缩进对代码块进行分组。看起来代码使用4个空格(或一个制表符)用于缩进,除了第30行到第35行外,其中只有两个空格。确保缩进在你的代码中是一致的,它应该可以解决你的问题。
更新:有了您的新错误,请确保您符合是否使用空格或制表符。浏览代码的每一行,每个标签使用4个空格,或者确保使用标签来达到正确的缩进。在固定用凹槽
的更多信息:How to fix python indentation 还检查了这一点:http://www.annedawson.net/Python_Spaces_Indentation.html
尝试使用Google的压痕和Python更多的信息,你解决了这个代码。
谢谢@Tyler Ferraro - 我在上面更新了我的问题,您的解决方案有效,现在显示出不同的错误。 –
看起来你正在混合制表符和空格来缩进。不要那样使用制表符或(更好的)空格来缩进。尝试使用'python -tt'运行代码 – jfs
'python -tt'很好,向我展示了你所说的'TabError:压缩中制表符和空格的不一致使用'。尽管我没有看到代码有什么问题。它现在正在使用标签。我已经更新了我的代码。我得到的错误是'真的';'线。 –
*“我看不出代码有什么问题”* - 不要混合使用缩进的制表符和空格:它是Python语法的一部分。我看到您的问题中的代码同时使用空格和制表符来缩进 – jfs