0

I switch between multiple computers for work and until we get a server running for our data, I have to manually change the path to a file that stores my masking. This annoyed me, since I switch a lot and the file paths are different. So, I'm trying to use socket to manage the file paths on my different computers. This is the code so far:

import socket

hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
    
if ip_address is '124.0.1.1':
    print('Working on laptop 1:')
    masked_data = '/mnt/c/Users/file/path/woot/woot'
else:
    raise ValueError('Which computer are you on? Need to know for mask filepath...')
    exit() 

What I'm wanting is essentially this: 1) Pull IP off the computer, 2) if it's laptop 1 use the IP from that computer and follow that file path, 3) if it's not, raise the error. (I'll update this for a few computers, but who needs complication here?)

The issue I'm having is this: When I run the script as shown above, it skips the if statement and throws the error. But, if I add the string that the line socket.gethostbyname(hostname) outputs, it works fine.

i.e., the code above does not work, but the code below does:

import socket

ip_address = '124.0.1.1'
if ip_address is '124.0.1.1':
    print('Working on laptop 1:')
    masked_data = '/mnt/c/Users/file/path/woot/woot'
else:
    raise ValueError('Which computer are you on? Need to know for mask filepath...')
    exit() 

In Ipython, when I run the script and check what ip_address is, it's literally a string with the IP address. i.e.,

In [1]: hostname = socket.gethostname()
In [2]: ip_address = socket.gethostbyname(hostname)
In [3]: ip_address
Out[3]: '124.0.1.1'  

I don't know what's going on and I'm not sure why this doesn't work.

halfer
  • 19,824
  • 17
  • 99
  • 186
NoVa
  • 317
  • 3
  • 15

1 Answers1

1

You might find this interesting: String comparison in Python: is vs. ==

Try using == to compare the strings instead of is. It is comparing the underlying reference, which is why it is not equal in the first program.

Peter S
  • 827
  • 1
  • 8
  • 24