When I run this Python3 script from the command line or from Thonny I get correct results. When I run it through crontab the variables ipaddress an ssid stay empty.

Can anyone tell me why? Any suggestions to solve it?

import dweepy, os

ipaddress = os.popen("ifconfig wlan0 | grep 'inet' | awk '/inet / {print $2}'").read()
ssid = os.popen("iwconfig wlan0 | grep 'ESSID' | awk '{print $4}' | awk -F\\\" '{print $2}'").read()

data = ssid[:-1] + ' ' + ipaddress[:-1]

dweepy.dweet_for('NorthWestern', {'here I am':data})

This script should let me know the ip address and the SSID of the wifi to which my headless Pi is connected.

Edit: this is the line in crontab:

* * * * * python3 /home/pi/PythonON5MF/send_ip_v001.py &
  • 1
    Please can you provide the full contents of your crontab. – Steve Amor Jun 18 '19 at 5:48
  • Do you start it from cron at reboot? Most likely, it is run before the WLAN is connected. Try to start the same script at a later time. – RalfFriedl Jun 18 '19 at 6:00
  • no I don't start it at reboot, I let it run every minute for testing. When I have this working I'll modify the script to only send me a dweet if SSID/IP change – ON5MF Jurgen Jun 18 '19 at 6:18
  • It is difficult to understand what your actual question is. Don't you know the SSID - if so how does the Pi connect? Is there any reason to use that convoluted popen when you could just use hostname -I to get the IP address? The "&" in cron seems superfluous for a script that runs once. – Milliways Jun 18 '19 at 6:45
  • The question is why the os.popen() does not give a result when the script is run in crontab. I want the Pi to let me know to which SSID it is connected and what is its IP address. I have a few different wifi routers and when I move around I want to know to which router it is connected. – ON5MF Jurgen Jun 18 '19 at 6:53

I found the solution... add sudo inside de os.popen() command:

ipaddress = os.popen("sudo ifconfig wlan0 | grep 'inet' | awk '/inet / {print $2}'").read()
| improve this answer | |

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.