AttributeError:“NoneType”对象没有属性“group”

2024-07-04 14:26:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: andtheoutputgroup传感器currentfloathas
2条回答

显然output不包含预期的字符串。(当它是通过调用echo 18生成时,它应该如何生成?)因此

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

返回None,其中没有

  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。您的regex搜索似乎找不到匹配项。如果正则表达式搜索可能失败,则需要显式处理该场景:

if matches is None:
    ....

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

与我试图告诉您如何准确地解决问题不同,您要学习的要点是如何解释这个特定的错误消息。

相关问题 更多 >

    热门问题