【问题标题】:Python Check for Internet Connection working with Raspberry PiPython 检查与 Raspberry Pi 一起使用的 Internet 连接
【发布时间】:2014-04-18 16:40:07
【问题描述】:

我正在用许多树莓派为我的家构建一个安全摄像头系统。每个摄像头系统的其中一件事是显示互联网连接存在的灯。为此,我使用了在python check to see if host is connected to network 找到的代码并将其修改为。

#! /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 运行代码时,错误显示为:

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

有人知道这个问题吗?抱歉,如果它是基本的,我是 Python 编程的新手。简而言之,我希望当存在互联网连接时,插针 8 上的灯会亮起。

谢谢!

【问题讨论】:

  • 看起来您正在混合使用制表符和空格进行缩进。不要使用制表符或(更好的)空格进行缩进。尝试使用python -tt运行代码
  • 那个'python -tt'很好,告诉我你说的'TabError:缩进中制表符和空格的不一致使用'。我看不出代码有什么问题。它现在一直在使用标签。我已经更新了上面的代码。我得到的错误是'while true;'行。
  • “我看不出代码有什么问题” -- 不要混合使用制表符和空格来缩进:它是 Python 语法的一部分。我看到您问题中的代码同时使用空格和制表符进行缩进
  • @MediaStreet 你能编辑你的答案以显示你提到的新错误吗?
  • 嗨@Winny 抱歉耽搁了。如果您转到dropbox.com/sh/fxa3vluhdopac29/GCbQYF15fs,您可以查看我收到的 Py 文件和错误。提前致谢!

标签: python raspberry-pi internet-connection


【解决方案1】:

Python 对缩进非常挑剔,因为它使用缩进对代码块进行分组。似乎代码在任何地方都使用 4 个空格(或一个制表符)进行缩进,除了第 30 到 35 行,它只有两个空格。确保整个代码中的缩进是一致的,它应该可以解决您的问题。

更新:对于您的新错误,请确保您使用的是空格还是制表符。遍历代码的每一行,每个制表符使用 4 个空格,或者确保它使用制表符来达到正确的缩进。

更多关于修复缩进的信息:How to fix python indentation 另请查看:http://www.annedawson.net/Python_Spaces_Indentation.html

在修复此代码时,请尝试在谷歌上搜索有关缩进和 Python 的更多信息。

【讨论】:

  • 谢谢@Tyler Ferraro - 我在上面更新了我的问题,你的解决方案有点奏效,现在它显示了一个不同的错误。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 2017-09-27
  • 1970-01-01
  • 2022-07-17
  • 2018-04-08
  • 2020-04-20
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多