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

2 投票
2 回答
14907 浏览
提问于 2025-04-18 00:07

请帮帮我,我正在尝试使用树莓派的PIR传感器,将传感器收集到的数据(是1还是0)传输到网络服务上,但我遇到了这个错误。

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 个回答

1

在你写下这段代码的时候,

matches.group(...)

变量 matches 的值是 None。这说明你的正则表达式搜索没有找到任何匹配的内容。如果正则表达式搜索有可能失败,那你就需要特别处理这种情况:

if matches is None:
    ....

或者,真正的问题可能是你用来进行搜索的代码本身就有问题。

与其让我告诉你具体该怎么做来解决这个问题,最重要的是你要学会如何理解这个特定的错误信息。

3

那么显然,output里并没有我们期待的字符串。(它是通过调用echo 18生成的,怎么可能有呢?)所以,

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

返回的是None,而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

撰写回答