kflmiami420
Posts: 62
Joined: Thu Mar 21, 2019 6:54 pm

Problem running mypi.py on Pi Zero W

Sat Jun 22, 2019 12:12 am

Hi I have this program

Code: Select all

#!/usr/bin/python
#--------------------------------------
#
#                mypi.py
#  Functions to display Pi properties
#
#  If called directly outputs :
#  - Pi Model
#  - Revision number
#  - Serial number
#  - Python version
#  - I2C,SPI and Bluetooth status
#  - Mac address
#  - IP address
#  - CPU temperature
#  - GPU temperature
#
# Author : Matt Hawkins
# Date   : 06/12/2017
#
# https://www.raspberrypi-spy.co.uk/
#
#--------------------------------------
import platform
import subprocess
import os

# Define functions

def getModel():
  # Extract Pi Model string
  try:
    mymodel = open('/proc/device-tree/model').readline()
  except:
    mymodel = "Error"

  return mymodel

def getSerial():
  # Extract serial from cpuinfo file
  mycpuserial = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:6]=='Serial':
        mycpuserial = line[10:26]
    f.close()
  except:
    mycpuserial = "Error"

  return mycpuserial

def getRevision():
  # Extract board revision from cpuinfo file
  myrevision = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:8]=='Revision':
        myrevision = line[11:-1]
    f.close()
  except:
    myrevision = "Error"

  return myrevision

def getEthName():
  # Get name of Ethernet interface
  try:
    for root,dirs,files in os.walk('/sys/class/net'):
      for dir in dirs:
        if dir[:3]=='enx' or dir[:3]=='eth':
          interface=dir
  except:
    interface="None"
  return interface
  
def getMAC(interface='eth0'):
  # Return the MAC address of named Ethernet interface
  try:
    line = open('/sys/class/net/%s/address' %interface).read()
  except:
    line = "None"
  return line[0:17]
  
def getIP(interface='eth0'):
  # Read ifconfig.txt and extract IP address
  try:
    filename = 'ifconfig_' + interface + '.txt'
    os.system('ifconfig ' + interface + ' > /home/pi/' + filename)
    f = open('/home/pi/' + filename, 'r')
    line = f.readline() # skip 1st line
    line = f.readline() # read 2nd line
    line = line.strip()
    f.close()

    if line.startswith('inet '):
      a,b,c = line.partition('inet ')
      a,b,c = c.partition(' ')
      a=a.replace('addr:','')
    else:
      a = 'None'

    return a

  except:
    return 'Error'

def getCPUtemp():
  # Extract CPU temp
  try:
    temp = subprocess.check_output(['vcgencmd','measure_temp'])
    temp = temp[5:-3]
  except:
    temp = '0.0'
  temp = '{0:.2f}'.format(float(temp))
  return str(temp)

def getGPUtemp():
  # Extract GPU temp
  try:
    temp = subprocess.check_output(['cat','/sys/class/thermal/thermal_zone0/temp'])
    temp = float(temp)/1000
  except:
    temp = 0.0
  temp = '{0:.2f}'.format(temp)
  return temp

def getRAM():
  # free -m
  output = subprocess.check_output(['free','-m'])
  lines = output.splitlines()
  line  = str(lines[1])
  ram = line.split()
  # total/free  
  return (ram[1],ram[3])

def getDisk():
  # df -h
  output = subprocess.check_output(['df','-h'])
  lines = output.splitlines()
  line  = str(lines[1])
  disk  = line.split()
  # total/free
  return (disk[1],disk[3])

def getCPUspeed():
  # Get CPU frequency
  try:
    output = subprocess.check_output(['vcgencmd','get_config','arm_freq'])
    output = output.decode()
    lines = output.splitlines()
    line  = lines[0]
    freq = line.split('=')
    freq = freq[1]
  except:
    freq = '0'
  return freq

def getUptime():
  # uptime
  # tupple uptime, 5 min load average
  return 0

def getPython():
  # Get current Python version
  # returns string
  pythonv = platform.python_version()
  return pythonv

def getSPI():
  # Check if SPI bus is enabled
  # by checking for spi_bcm2### modules
  # returns a string
  spi = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"spi_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='spi_bcm2':
      spi = "True"
  except:
    pass
  return spi

def getI2C():
  # Check if I2C bus is enabled
  # by checking for i2c_bcm2### modules
  # returns a string
  i2c = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"i2c_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='i2c_bcm2':
      i2c = "True"
  except:
    pass
  return i2c

def getBT():
  # Check if Bluetooth module is enabled
  # returns a string
  bt = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"bluetooth"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:9]==b'bluetooth':
      bt = "True"
  except:
    pass
  return bt

if __name__ == '__main__':
  # Script has been called directly

  myRAM = getRAM()
  myDisk = getDisk()
  ethName = getEthName()

  print("----------------------------------------")
  print("Pi Model             : " + getModel())
  print("----------------------------------------")
  print("System               : " + platform.platform())
  print("Revision Number      : " + getRevision())
  print("Serial Number        : " + getSerial())
  print("Python version       : " + platform.python_version())
  print("----------------------------------------")
  print("I2C enabled          : " + getI2C())
  print("SPI enabled          : " + getSPI())
  print("Bluetooth enabled    : " + getBT())
  print("----------------------------------------")
  print("Ethernet Name        : " + ethName)  
  print("Ethernet MAC Address : " + getMAC(ethName))
  print("Ethernet IP Address  : " + getIP(ethName))
  print("Wireless MAC Address : " + getMAC('wlan0'))
  print("Wireless IP Address  : " + getIP('wlan0'))
  print("----------------------------------------")
  print("CPU Clock            : " + getCPUspeed() + "MHz")
  print("CPU Temperature      : " + getCPUtemp() + u"\u00b0" +"C")
  print("GPU Temperature      : " + getGPUtemp() + u"\u00b0" +"C")
  print("RAM (Available)      : " + myRAM[0] + "MB (" + myRAM[1] + "MB)")
  print("Disk (Available)     : " + myDisk[0] + " (" + myDisk[1] + ")")
  print("----------------------------------------")
the output is this
Pi Model : Raspberry Pi 3 Model B Rev 1.2
----------------------------------------
System : Linux-4.19.42-v7+-armv7l-with-debian-9.9
Revision Number : a22082
Serial Number : 00000000a0dffe96
Python version : 2.7.13
----------------------------------------
I2C enabled : True
SPI enabled : True
Bluetooth enabled : True
----------------------------------------
Ethernet Name : eth0
Ethernet MAC Address : b8:27:eb:df:
Ethernet IP Address : None
Wireless MAC Address : b8:27:eb:8a:xx:xx #added xx to protect privacy in forum
Wireless IP Address : 192.168.1.xxx #added xx to protect privacy in forum
----------------------------------------
CPU Clock : 1200MHz
CPU Temperature : 56.90°C
GPU Temperature : 57.46°C
RAM (Available) : 969MB (480MB)
Disk (Available) : 12G (4.8G)
----------------------------------------



but it does not run on Pi Zero W

I had to comment out the

Code: Select all

print("Ethernet Name        : " + ethName)  
  print("Ethernet MAC Address : " + getMAC(ethName))
  print("Ethernet IP Address  : " + getIP(ethName))
  print("Wireless MAC Address : " + getMAC('wlan0'))
  print("Wireless IP Address  : " + getIP('wlan0'))
Does anyone know what the proper syntax is for getting this code or something that will display that info
Last edited by kflmiami420 on Sat Jun 22, 2019 4:12 pm, edited 1 time in total.

saltydog
Posts: 39
Joined: Mon Dec 24, 2012 10:40 am

Re: Problem running mypi.py on Pi Zero W

Sat Jun 22, 2019 6:07 am

The pi zero doesn't have an Ethernet port.
The wireless addr should return a result

Chris

kflmiami420
Posts: 62
Joined: Thu Mar 21, 2019 6:54 pm

Re: Problem running mypi.py on Pi Zero W

Sat Aug 17, 2019 8:30 am

Just Updated and got the code working


I wanted to share the revised script



# mypi.py
# Functions to display Pi properties
#
# If called directly outputs :
# - Pi Model
# - Revision number
# - Serial number
# - Python version
# - I2C,SPI and Bluetooth status
# - Mac address
# - IP address
# - CPU temperature
# - GPU temperature

Code: Select all

# revised 08-17-2019 
#!/usr/bin/python3
#--------------------------------------
#
#                mypi.py
#  Functions to display Pi properties
#
#  If called directly outputs :
#  - Pi Model
#  - Revision number
#  - Serial number
#  - Python version
#  - I2C,SPI and Bluetooth status
#  - Mac address
#  - IP address
#  - CPU temperature
#  - GPU temperature
#
# Author : Matt Hawkins
# Date   : 06/12/2017 Revised 08-17-2019 for my Pi Zero W (by kflmiami420)
#
# https://www.raspberrypi-spy.co.uk/
#
#--------------------------------------

import platform
import subprocess
import os
import socket

from uuid import getnode as get_mac

# Define functions

def getModel():
  # Extract Pi Model string
  try:
    mymodel = open('/proc/device-tree/model').readline()
  except:
    mymodel = "Error"

  return mymodel

def getSerial():
  # Extract serial from cpuinfo file
  mycpuserial = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:6]=='Serial':
        mycpuserial = line[10:26]
    f.close()
  except:
    mycpuserial = "Error"

  return mycpuserial

def getRevision():
  # Extract board revision from cpuinfo file
  myrevision = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:8]=='Revision':
        myrevision = line[11:-1]
    f.close()
  except:
    myrevision = "Error"

  return myrevision

def get_local_ip_address(target):
  ipaddr = ''
  try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect((target, 8000))
    ipaddr = s.getsockname()[0]
    s.close()
  except:
    pass

  return ipaddr

def getCPUtemp():
  # Extract CPU temp
  try:
    temp = subprocess.check_output(['vcgencmd','measure_temp'])
    temp = temp[5:-3]
  except:
    temp = '0.0'
  temp = '{0:.2f}'.format(float(temp))
  return str(temp)

def getGPUtemp():
  # Extract GPU temp
  try:
    temp = subprocess.check_output(['cat','/sys/class/thermal/thermal_zone0/temp'])
    temp = float(temp)/1000
  except:
    temp = 0.0
  temp = '{0:.2f}'.format(temp)
  return temp

def getRAM():
  # free -m
  output = subprocess.check_output(['free','-m'])
  lines = output.splitlines()
  line  = str(lines[1])
  ram = line.split()
  # total/free  
  return (ram[1],ram[3])

def getDisk():
  # df -h
  output = subprocess.check_output(['df','-h'])
  lines = output.splitlines()
  line  = str(lines[1])
  disk  = line.split()
  # total/free
  return (disk[1],disk[3])

def getCPUspeed():
  # Get CPU frequency
  try:
    output = subprocess.check_output(['vcgencmd','get_config','arm_freq'])
    output = output.decode()
    lines = output.splitlines()
    line  = lines[0]
    freq = line.split('=')
    freq = freq[1]
  except:
    freq = '0'
  return freq

def getUptime():
  # uptime
  # tupple uptime, 5 min load average
  return 0

def getPython():
  # Get current Python version
  # returns string
  pythonv = platform.python_version()
  return pythonv

def getSPI():
  # Check if SPI bus is enabled
  # by checking for spi_bcm2### modules
  # returns a string
  spi = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"spi_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='spi_bcm2':
      spi = "True"
  except:
    pass
  return spi

def getI2C():
  # Check if I2C bus is enabled
  # by checking for i2c_bcm2### modules
  # returns a string
  i2c = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"i2c_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='i2c_bcm2':
      i2c = "True"
  except:
    pass
  return i2c

def getBT():
  # Check if Bluetooth module is enabled
  # returns a string
  bt = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"bluetooth"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:9]==b'bluetooth':
      bt = "True"
  except:
    pass
  return bt

if __name__ == '__main__':
  # Script has been called directly

  myRAM = getRAM()
  myDisk = getDisk()
  host = socket.gethostname()
  mac = get_mac()

  macString = ':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2))


  print("----------------------------------------")
  print("Pi Model             : " + getModel())
  print("----------------------------------------")
  print("Host                 :", host)
  print("----------------------------------------")
  print("System               : " + platform.platform())
  print("Revision Number      : " + getRevision())
  print("Serial Number        : " + getSerial())
  print("Python version       : " + platform.python_version())
  print("----------------------------------------")
  print("I2C enabled          : " + getI2C())
  print("SPI enabled          : " + getSPI())
  print("Bluetooth enabled    : " + getBT())
  print("----------------------------------------")
  print("CPU Clock            : " + getCPUspeed() + "MHz")
  print("CPU Temperature      : " + getCPUtemp() + u"\u00b0" +"C")
  print("GPU Temperature      : " + getGPUtemp() + u"\u00b0" +"C")
  print("RAM (Available)      : " + myRAM[0] + "MB (" + myRAM[1] + "MB)")
  print("Disk (Available)     : " + myDisk[0] + " (" + myDisk[1] + ")")
  print("----------------------------------------")
  print("Wireless IP Address  : " + get_local_ip_address('10.0.1.1'))
  print("Wireless MAC Address : " + macString )


hippy
Posts: 6242
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: Problem running mypi.py on Pi Zero W

Sat Aug 17, 2019 1:16 pm

kflmiami420 wrote:
Sat Jun 22, 2019 12:12 am
I had to comment out the ...
You could probably have checked 'ethName' to see if it were None or an empty string, and then only execute the ethernet stuff if there is ethernet available. You could wrap all that with 'try-except' for extra protection.

That way the exact same code should run on any Pi variant. And it would then work and report the ethernet detail if it were a Zero with a USB-to-ethernet adapter attached.

You can do similar for WiFi, so the exact same code works for Pi variants which don't have WiFi on-board, those which may have USB-to-WiFi adapters plugged in.

kflmiami420
Posts: 62
Joined: Thu Mar 21, 2019 6:54 pm

Re: Problem running mypi.py on Pi Zero W

Sun Aug 18, 2019 9:46 pm

Thanks I will look into that. I really don't think anyone wants to work with boards that don't have wifi these days. ( I know I don't)
I have some pi 3 and some pi 4 but I mainly deal in the Pi Zero W so that's why I set it up for the Pi W.

The original code does check for ethernet ip and mac address.

https://bitbucket.org/MattHawkinsUK/rpi ... on/mypi.py

Code: Select all

#!/usr/bin/python
#--------------------------------------
#
#                mypi.py
#  Functions to display Pi properties
#
#  If called directly outputs :
#  - Pi Model
#  - Revision number
#  - Serial number
#  - Python version
#  - I2C,SPI and Bluetooth status
#  - Mac address
#  - IP address
#  - CPU temperature
#  - GPU temperature
#
# Author : Matt Hawkins
# Date   : 06/12/2017
#
# https://www.raspberrypi-spy.co.uk/
#
#--------------------------------------
import platform
import subprocess
import os

# Define functions

def getModel():
  # Extract Pi Model string
  try:
    mymodel = open('/proc/device-tree/model').readline()
  except:
    mymodel = "Error"

  return mymodel

def getSerial():
  # Extract serial from cpuinfo file
  mycpuserial = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:6]=='Serial':
        mycpuserial = line[10:26]
    f.close()
  except:
    mycpuserial = "Error"

  return mycpuserial

def getRevision():
  # Extract board revision from cpuinfo file
  myrevision = "Error"
  try:
    f = open('/proc/cpuinfo','r')
    for line in f:
      if line[0:8]=='Revision':
        myrevision = line[11:-1]
    f.close()
  except:
    myrevision = "Error"

  return myrevision

def getEthName():
  # Get name of Ethernet interface
  try:
    for root,dirs,files in os.walk('/sys/class/net'):
      for dir in dirs:
        if dir[:3]=='enx' or dir[:3]=='eth':
          interface=dir
  except:
    interface="None"
  return interface
  
def getMAC(interface='eth0'):
  # Return the MAC address of named Ethernet interface
  try:
    line = open('/sys/class/net/%s/address' %interface).read()
  except:
    line = "None"
  return line[0:17]
  
def getIP(interface='eth0'):
  # Read ifconfig.txt and extract IP address
  try:
    filename = 'ifconfig_' + interface + '.txt'
    os.system('ifconfig ' + interface + ' > /home/pi/' + filename)
    f = open('/home/pi/' + filename, 'r')
    line = f.readline() # skip 1st line
    line = f.readline() # read 2nd line
    line = line.strip()
    f.close()

    if line.startswith('inet '):
      a,b,c = line.partition('inet ')
      a,b,c = c.partition(' ')
      a=a.replace('addr:','')
    else:
      a = 'None'

    return a

  except:
    return 'Error'

def getCPUtemp():
  # Extract CPU temp
  try:
    temp = subprocess.check_output(['vcgencmd','measure_temp'])
    temp = temp[5:-3]
  except:
    temp = '0.0'
  temp = '{0:.2f}'.format(float(temp))
  return str(temp)

def getGPUtemp():
  # Extract GPU temp
  try:
    temp = subprocess.check_output(['cat','/sys/class/thermal/thermal_zone0/temp'])
    temp = float(temp)/1000
  except:
    temp = 0.0
  temp = '{0:.2f}'.format(temp)
  return temp

def getRAM():
  # free -m
  output = subprocess.check_output(['free','-m'])
  lines = output.splitlines()
  line  = str(lines[1])
  ram = line.split()
  # total/free  
  return (ram[1],ram[3])

def getDisk():
  # df -h
  output = subprocess.check_output(['df','-h'])
  lines = output.splitlines()
  line  = str(lines[1])
  disk  = line.split()
  # total/free
  return (disk[1],disk[3])

def getCPUspeed():
  # Get CPU frequency
  try:
    output = subprocess.check_output(['vcgencmd','get_config','arm_freq'])
    output = output.decode()
    lines = output.splitlines()
    line  = lines[0]
    freq = line.split('=')
    freq = freq[1]
  except:
    freq = '0'
  return freq

def getUptime():
  # uptime
  # tupple uptime, 5 min load average
  return 0

def getPython():
  # Get current Python version
  # returns string
  pythonv = platform.python_version()
  return pythonv

def getSPI():
  # Check if SPI bus is enabled
  # by checking for spi_bcm2### modules
  # returns a string
  spi = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"spi_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='spi_bcm2':
      spi = "True"
  except:
    pass
  return spi

def getI2C():
  # Check if I2C bus is enabled
  # by checking for i2c_bcm2### modules
  # returns a string
  i2c = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"i2c_bcm2"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:8]=='i2c_bcm2':
      i2c = "True"
  except:
    pass
  return i2c

def getBT():
  # Check if Bluetooth module is enabled
  # returns a string
  bt = "False"
  try:
    c=subprocess.Popen("lsmod",stdout=subprocess.PIPE)
    gr=subprocess.Popen(["grep" ,"bluetooth"],stdin=c.stdout,stdout=subprocess.PIPE)
    output = gr.communicate()[0]
    if output[:9]==b'bluetooth':
      bt = "True"
  except:
    pass
  return bt

if __name__ == '__main__':
  # Script has been called directly

  myRAM = getRAM()
  myDisk = getDisk()
  ethName = getEthName()

  print("----------------------------------------")
  print("Pi Model             : " + getModel())
  print("----------------------------------------")
  print("System               : " + platform.platform())
  print("Revision Number      : " + getRevision())
  print("Serial Number        : " + getSerial())
  print("Python version       : " + platform.python_version())
  print("----------------------------------------")
  print("I2C enabled          : " + getI2C())
  print("SPI enabled          : " + getSPI())
  print("Bluetooth enabled    : " + getBT())
  print("----------------------------------------")
  print("Ethernet Name        : " + ethName)  
  print("Ethernet MAC Address : " + getMAC(ethName))
  print("Ethernet IP Address  : " + getIP(ethName))
  print("Wireless MAC Address : " + getMAC('wlan0'))
  print("Wireless IP Address  : " + getIP('wlan0'))
  print("----------------------------------------")
  print("CPU Clock            : " + getCPUspeed() + "MHz")
  print("CPU Temperature      : " + getCPUtemp() + u"\u00b0" +"C")
  print("GPU Temperature      : " + getGPUtemp() + u"\u00b0" +"C")
  print("RAM (Available)      : " + myRAM[0] + "MB (" + myRAM[1] + "MB)")
  print("Disk (Available)     : " + myDisk[0] + " (" + myDisk[1] + ")")
  print("----------------------------------------")

I have now broken the code as it is not reporting the status of the I2C , SPI , Bluetooth
Last edited by kflmiami420 on Mon Aug 19, 2019 9:25 pm, edited 1 time in total.

Andyroo

Re: Problem running mypi.py on Pi Zero W

Sun Aug 18, 2019 10:10 pm

I really don't think anyone wants to work with boards that don't have wifi these days
I have a couple of Pi boards (a 3B and 3B+) that are Ethernet only and have both the WiFi and Bluetooth disabled in config.txt

Neither need these functions (they are inches from a switch) so I disabled them

I also have a Zero connected via an USB link that does not have a WiFi chip but gets its LAN connected via a Mac.

Never assume a user will not do something just because you cannot think of a reason why :lol: Users do odd things on a daily basis and defensive programming is a must.

With the faster 4 Ethernet ports you may see more and more boards without WiFi up and running.

Edit: Also consider multiple WiFi / LAN adapters...

User avatar
DougieLawson
Posts: 36558
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Problem running mypi.py on Pi Zero W

Mon Aug 19, 2019 12:01 am

Code: Select all

    os.system('ifconfig ' + interface + ' > /home/pi/' + filename)
    f = open('/home/pi/' + filename, 'r')
That's a very bad programming technique. It's much better to use /tmp for temporary files rather than hard-coding a directory that may not exist.

Here's an example of how you can get IPv4 Address and HW MAC based on finding the interface names in /sys/class/net

Code: Select all

#!/usr/bin/python

import fcntl, socket, struct
from os import walk

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]

def getIPAddr(ifname):
    if (ifname == "lo"):
        return "127.0.0.1"
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
         info = fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))
    except:
         return "No address assigned"
    return socket.inet_ntoa(info[20:24])

f = []
path = '/sys/class/net'

for (dirpath, dirnames, filename) in walk(path):
    f.extend(dirnames)
    break

for iface in f:
    print "Interface:", iface
    print "IPv4 Addr:", getIPAddr(iface)
    print "HW MAC Addr:", getHwAddr(iface)
    print "-----------------------------"
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

kflmiami420
Posts: 62
Joined: Thu Mar 21, 2019 6:54 pm

Re: Problem running mypi.py on Pi Zero W

Mon Aug 19, 2019 9:22 pm

DougieLawson Thank you for the code and the info on how to clean the code up

I want to add the results from i2cdetect -y 1 to the output but I am lost or dont know if it is even possible

User avatar
DougieLawson
Posts: 36558
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Problem running mypi.py on Pi Zero W

Mon Aug 19, 2019 9:32 pm

This is a bit crude, but gives you the idea how to detect I2C devices.

Code: Select all

#!/usr/bin/python
import smbus
import time
bus = smbus.SMBus(1)
low_addr=0x03
hi_addr=0x78
for addr in range(low_addr, hi_addr):
  try:
    bus.read_byte_data(addr,0x00)
    print "Addr: ", hex(addr)," OK"
  except:
    print "Addr: ", hex(addr),"BAD"
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

kflmiami420
Posts: 62
Joined: Thu Mar 21, 2019 6:54 pm

Re: Problem running mypi.py on Pi Zero W

Tue Aug 20, 2019 2:21 am

DougieLawson

Thank you I will implement that

Return to “Python”