1

I am trying to get my raspberry Pi to display it's IP to my LCD display. I need to execute this command 'hostname -I' using python in a python script I have almost successfully made , grab the result text( which will be the IP) string, and pass it to my 20x4 LCD display. This is my attempt:

  j=os.popen("hostname -I")
  lcd_byte(LCD_LINE_2, LCD_CMD)
  lcd_string(str(j),1)

I am getting no errors however my LCD display is saying: <open file 'hostname' and then it cuts off.

  • My LCD is saying: "<open file 'hostname" and then it cuts off. – George Cooper Oct 14 '17 at 0:26
2

Expanding Dr.Rabbit's answer a little, what you want to do is actually run a shell command (hostname -I), which returns the IP address of the machine running that command. As the Python script you're running is one process and the shell command is also another process, what you need to do from your Python script is

  • run the shell command
  • wait till it has run
  • retrieve in a variable the text (the IP address) it has written to the subprocess' standard output, which you send to the display

and subprocess.check_output does exactly that. What popen does is only prepare a sub-process, which the calling script still needs to interact with hence the bizarre garbage text you noticed.

However note that shell = True poses a security risk:

17.1.1. Using the subprocess Module

Warning : Using shell=True can be a security hazard. See the warning under Frequently Used Arguments for details.

A safer approach would be to run command hostname -I and clean up the returned text from within Python:

import subprocess

IP = subprocess.check_output(["hostname", "-I"]).split()[0]
print str(IP)

#send it to the LCD
lcd_string(str(IP),1)
  • I agree this is the better approach, unless your in a closed network. – Dr.Rabbit Oct 14 '17 at 11:33
1

Run it using subprocess

import subprocess

cmd = "hostname -I | cut -d\' \' -f1"
IP = subprocess.check_output(cmd, shell = True )
print str(IP)

#send it to the LCD
lcd_string(str(IP),1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.