在树莓派上检查Python的互联网连接

1 投票
1 回答
5716 浏览
提问于 2025-04-18 03:11

我正在用几个树莓派搭建一个家庭监控摄像头系统。每个摄像头系统都会有一个灯,用来显示是否有互联网连接。为此,我使用了在这个链接找到的代码,并对其进行了修改。

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

但是当我在我的树莓派上运行这段代码时,出现了以下错误:

pi@raspberrypi ~/Desktop $     while True:
>               ^
> TabError: inconsistent use of tabs and spaces in indentation
> ^C

有人知道是什么问题吗?如果这是个基础问题,我很抱歉,我刚开始学习Python编程。简单来说,我希望当有互联网连接时,8号引脚上的灯会亮起来。

谢谢!

1 个回答

0

Python 对代码的缩进要求非常严格,因为它用缩进来区分代码块。看起来你的代码在大部分地方都用了 4 个空格(或者一个制表符)来缩进,但在第 30 行到第 35 行之间却只用了 2 个空格。确保你的代码缩进方式一致,这样就能解决你的问题。

更新:针对你新的错误,确保你在使用空格和制表符时保持一致。逐行检查你的代码,要么每个制表符用 4 个空格,要么就全部使用制表符来达到正确的缩进。

关于修复缩进的更多信息:如何修复 Python 缩进。还有这个链接:http://www.annedawson.net/Python_Spaces_Indentation.html

在修复代码时,可以尝试在网上搜索更多关于缩进和 Python 的信息。

撰写回答