2014-04-17 74 views
1

我正在爲我的家建立一個安全攝像機系統,其中包括一些樹莓派。每個攝像頭系統的其中一項功能是顯示互聯網連接的亮點。爲此,我使用了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上的指示燈將亮起。

謝謝!

+0

看起來你正在混合製表符和空格來縮進。不要那樣使用製表符或(更好的)空格來縮進。嘗試使用'python -tt'運行代碼 – jfs

+0

'python -tt'很好,向我展示了你所說的'TabError:壓縮中製表符和空格的不一致使用'。儘管我沒有看到代碼有什麼問題。它現在正在使用標籤。我已經更新了我的代碼。我得到的錯誤是'真的';'線。 –

+0

*「我看不出代碼有什麼問題」* - 不要混合使用縮進的製表符和空格:它是Python語法的一部分。我看到您的問題中的代碼同時使用空格和製表符來縮進 – jfs

回答

0

Python對縮進非常挑剔,因爲它使用縮進對代碼塊進行分組。看起來代碼使用4個空格(或一個製表符)用於縮進,除了第30行到第35行外,其中只有兩個空格。確保縮進在你的代碼中是一致的,它應該可以解決你的問題。

更新:有了您的新錯誤,請確保您符合是否使用空格或製表符。瀏覽代碼的每一行,每個標籤使用4個空格,或者確保使用標籤來達到正確的縮進。在固定用凹槽

的更多信息:How to fix python indentation 還檢查了這一點:http://www.annedawson.net/Python_Spaces_Indentation.html

嘗試使用Google的壓痕和Python更多的信息,你解決了這個代碼。

+0

謝謝@Tyler Ferraro - 我在上面更新了我的問題,您的解決方案有效,現在顯示出不同的錯誤。 –