0

I have below code that I have written

class Test:
    def __init__(self,value):
        ''' Constructor. '''
        self.ext_ip_address = value
    def ip_address_changed(self):
        with open(IP_ADDR, 'r') as ip_address:
            ip_addr = ip_address.read().replace('\n','')
            if not ip_address == self.ext_ip_address:
                self.ext_ip_address = ip_address
                print 'IP ADDR', ip_addr
                print 'EXT IP ADDR', self.ext_ip_address
                return True
        return False



# Run following code when the program starts
if __name__ == '__main__':
   test_obj = Test('')
   if test_obj.ip_address_changed():
      print "IP changed"
   else:
      print "IP constant"

Here I am reading the IP address of a machine from file (i.e. ip_addr local variable), then I am checking whether the IP address of machine is changed from the last value (i.e. self.ext_ip_address). Then I am trying to print the values of both variables ip_addr and self.ext_ip_address. For ip_addr, I am getting the proper value. But for self.ext_ip_address I am getting strange value as below:

IP ADDR 192.168.44.100
EXT IP ADDR <open file '/usr/local/bin/data/ip_address.dat', mode 'r' at 0xb772e230>

Please let me know what is the reason for this. Thanks in advance!!!

3
  • You should use ip_address.read().strip() in instance of ip_address.read().replace('\n','') to avoid trailing whitespaces messing with your values Commented May 19, 2017 at 7:20
  • @VMRuiz Thanks for the tip, but my comment was not meant as an answer. I was responding to a comment Kuro has posted, but apparently has deleted. Commented May 19, 2017 at 7:22
  • Sorry, I messed up with the names! Commented May 19, 2017 at 7:24

1 Answer 1

4

You mixed up ip_addr and ip_address in two places. ip_address is your file, which is what you wound up printing instead of the address you had in mind.

class Test:
    def __init__(self,value):
        ''' Constructor. '''
        self.ext_ip_address = value
    def ip_address_changed(self):
        with open(IP_ADDR, 'r') as ip_address:
            ip_addr = ip_address.read().strip()  # Per VMRuiz's comment
            if not ip_addr == self.ext_ip_address:  # HERE
                self.ext_ip_address = ip_addr  # AND HERE
                print 'IP ADDR', ip_addr
                print 'EXT IP ADDR', self.ext_ip_address
                return True
        return False

Clearer variable names will prevent this problem in the future.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.