Nino Stephen
Nino Stephen

Reputation: 33

why is the regex function always popping up the Attribute Error?

I have been writing a function in python to get the IP of a computer. The code is given below :

    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

I know this is not a good way to get the IP of a machine. The problem is that the AttributeError pops up every single time. Why is it happening? why can't a match be found?

Upvotes: 1

Views: 59

Answers (1)

Deca
Deca

Reputation: 1235

I ran it in my local. Found 4 things be be modified!

a) regex:- \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}

b) trim for any extra space while reading:- file.readline().strip()

c) If it comes to end of line, break the while:-

if line == '':
    break

d) Instead of re.search, do re.finall

The modified code that works in my system without AttributeError is:-

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

Upvotes: 1

Related Questions