为什么正则表达式函数总是弹出属性错误?

时间:2016-06-28 10:15:22

标签: python regex attributeerror

我一直在python中编写一个函数来获取计算机的IP。代码如下:

    def getip(self):

            self.path = "/root"
            self.iplist = []
            os.chdir(self.path)
            os.system("ifconfig > ipfinder")
            try:

                    file = open("ipfinder","r")
                    self.pattern = '(\d{1,3}\.){3}\d{1,3}'
                    while True:
                            line = file.readline()
                            try:

                                    ip = re.search(self.pattern, line).group()
                                    self.iplist.append(ip)
                            except AttributeError:
                                    pass

                    file.close()

            except  EOFError:
                    for ip in self.iplist:
                            print ip

我知道这不是获取机器IP的好方法。问题是每次都会弹出AttributeError。为什么会这样?为什么找不到匹配?

1 个答案:

答案 0 :(得分:1)

我在当地跑了。发现有4件事需要修改!

a)正则表达式: - \ d {1,3}。\ d {1,3}。\ d {1,3}。\ d {1,3}

b)在阅读时修剪任何额外的空间: - file.readline()。strip()

c)如果到了行尾,请打破时间: -

if line == '':
    break

d)而不是re.search,请执行re.finall

在我的系统中没有AttributeError的修改代码是: -

def getip(self):

    self.path = "/root"
    self.iplist = []
    os.chdir(self.path)
    os.system("ifconfig > ipfinder")
    try:

            file = open("ipfinder","r")
            self.pattern = '\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}'
            while True:
                    line = file.readline().strip()
                    if line == '':
                        break
                    try:

                            ip = re.findall(self.pattern, line)
                            self.iplist.append(ip)
                    except AttributeError:
                            pass

            file.close()

    except  EOFError:
            for ip in self.iplist:
                    print ip