AttributeError:'NoneType'对象没有属性'group'

时间:2014-03-27 08:17:56

标签: python raspberry-pi

请帮助,因为我正在尝试使用覆盆子pi 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)

2 个答案:

答案 0 :(得分:3)

然后显然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

答案 1 :(得分:1)

在你写的地方

matches.group(...)

匹配为None。您的正则表达式搜索似乎无法找到匹配项。如果正则表达式搜索可能失败,那么您需要明确处理该场景:

if matches is None:
    ....

或许真正的问题是您执行搜索的代码是错误的。

而不是我试图告诉你如何解决问题,你要学习的主要内容是如何解释这个特定的错误信息。