Search code examples
pythonbashraspberry-piboot

Python bash output into string


I have RaspberryPi and I've made a Python script that sends me an email when it boots up. The only problem that I have is the Pi changes IPs quite often (DHCP), so I want for it to also include output of commands:

hostname -I

curl ipinfo.io/ip

in the email.


Solution

  • This subprocess function returns the results of the commands in a string that you can attach to your email message:

    import subprocess
    host = subprocess.check_output(['hostname', '-I'], shell=True, universal_newlines=True) # a string is returned
    curl = subprocess.check_output(['curl', 'ipinfo.io/ip'], shell=True, universal_newlines=True)
    

    You can call rstrip() on both strings to get rid of any trailing newline character.