【问题标题】:AttributeError: 'NoneType' object has no attribute 'groups'AttributeError:“NoneType”对象没有属性“组”
【发布时间】:2015-02-16 19:59:22
【问题描述】:

我不知道我应该怎么问这个问题。如果我犯了任何错误,如果有人能纠正我将不胜感激。

我正在 Ubuntu 上用 python 编写程序。在那个程序中,我正在努力从连接到网络的 IP 地址(RaspberryPi)获取远程机器的 Mac 地址。

但在实际实践中,它给了我一个错误:

Traceback (most recent call last): File "Get_MacAddress_from_ip.py", line 9, in <module> mac = re.search(r"([a-fA-F0-9]{2}[:|\-]?){6}", s).groups()[0] AttributeError: 'NoneType' object has no attribute 'groups'

谁能指导我如何消除此错误?我的编码如下所示

from Tkinter import *
from subprocess import Popen, PIPE

ip = "192.168.2.34"
username = "pi"
remote_MAC="b8:27:eb:d2:84:ef"
pid = Popen(["arp", "-n", ip], stdout=PIPE)
s = pid.communicate()[0]
mac = re.search(r"([a-fA-F0-9]{2}[:|\-]?){6}", s).groups()[0]
mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
print mac

【问题讨论】:

  • 尝试打印字符串 "s" 并在其上打印 re.search 的结果(没有 groups() 东西)
  • 添加print s行后,打印192.168.2.34 (192.168.2.34) -- no entry是什么意思
  • 你为什么要两次调用 re.search?
  • 但是不可能有任何意义调用它一次,将结果分配给一个变量,然后立即用第二次调用的结果覆盖该变量。这与您根本没有打过第一次电话完全一样。
  • 很可能是这样,但这并不意味着第一次通话完全没有意义。

标签: python ubuntu ip attributeerror arp


【解决方案1】:

re.search 如果没有匹配项,则返回 None。尝试分配结果并检查它是否为无:

search = re.search(r"([a-fA-F0-9]{2}[:|\-]?){6}", s)
mac = None
if search:
    mac = search.groups()[0]
    # You can also do:
    #mac = search.group(0)
print mac

【讨论】:

  • 我只从完整的mac地址b8:27:eb:d2:84:ef获取ef
猜你喜欢
  • 2015-09-06
  • 1970-01-01
  • 2022-07-20
  • 2019-01-01
  • 2021-12-26
  • 2019-07-23
  • 2018-05-13
相关资源
最近更新 更多