簡體   English   中英

AttributeError:'NoneType'對象沒有屬性'group'

[英]AttributeError: 'NoneType' object has no attribute 'group'

請幫忙,因為我嘗試使用樹莓派Pir傳感器將Pir傳感器(為1或0)收集的數據傳輸到Web服務,但出現此錯誤

Traceback (most recent call last):
  File "pir_5.py", line 54, in <module>
    moveHold = float(matches.group(1))
AttributeError: 'NoneType' object has no attribute 'group'

這是我的代碼

while True :

    # Read PIR state
    Current_State = GPIO.input(GPIO_PIR)

    if Current_State==1 and Previous_State==0:
      # PIR is triggered
      output =  subprocess.check_output(["echo", "18"]);
      print "  Motion detected!"
      # Tell the Pi to run our speech script and speak the words
      # motion dtected! - anything after the .sh will be read out.
      matches = re.search("Current_State==1 and Previous_State==0", output)
      moveHold = float(matches.group(1))
      resultm = client.service.retrieveMove(moveHold)

      cmd_string = './speech.sh motion detected!'
      # now run the command on the Pi.
      os.system(cmd_string)
      # Record previous state
      Previous_State=1
    elif Current_State==0 and Previous_State==1:
      # PIR has returned to ready state
      print "  Ready"
      Previous_State=0

    # Wait for 10 milliseconds
    time.sleep(0.01)

那么顯然output中不包含預期的字符串。 (當通過調用echo 18生成它時,該怎么辦?)

  matches = re.search("Current_State==1 and Previous_State==0", output)

返回None ,沒有.group()

  moveHold = float(matches.group(1))

這樣您就可以得到上述例外。

您應該將其更改為

    matches = re.search("Current_State==1 and Previous_State==0", output)
    if matches:
        moveHold = float(matches.group(1))
        resultm = client.service.retrieveMove(moveHold)
        ...
    else:
        # code for if it didn't match

在你寫的那一點

matches.group(...)

比賽None 您的正則表達式搜索似乎找不到匹配項。 如果正則表達式搜索有可能失敗,那么您需要顯式處理該情況:

if matches is None:
    ....

也許真正的問題是執行搜索的代碼是錯誤的。

除了讓我確切地告訴您解決問題的方法外,您要學習的重點還在於如何解釋此特定錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM