Page 1 of 1

Check wi-fi status from python script

Posted: Tue Jan 31, 2017 2:33 pm
by scotty134
Hello to everybody!

I need to check wi-fi connection from code. I start looking for regular python wifi libraries, but RPi doesn't support it.
Can somebody help me to find way how I can check wi-fi connection/status?
Thanks in advance!

Regards,
Scotty

Re: Check wi-fi status from python script

Posted: Tue Jan 31, 2017 4:53 pm
by scruss
Maybe parse the output from the ifconfig wlan0 command? That will tell you if it's up, and has an IP address.

Re: Check wi-fi status from python script

Posted: Tue Jan 31, 2017 5:44 pm
by stderr
scotty134 wrote:Can somebody help me to find way how I can check wi-fi connection/status?
If you ping the connection, that is likely to keep it awake over the span. At least it's more likely to do so than not pinging it. You may wish to at least start doing this with the system's ping command as pinging requires running as root and it is set to do that with setuid or by some other means.

Re: Check wi-fi status from python script

Posted: Tue Jan 31, 2017 6:49 pm
by Davies

Code: Select all

import urllib
try:
    url = "https://www.google.com"
    urllib.urlopen(url)
    status = "Connected"
except:
    status = "Not connected"
print status
if status == "Connected":
    # do stuff...
will check for internet connection.

Code: Select all

check_output(['hostname', '-I'])
shows all IP's so if wifi is the only connection you could perhaps say(i dont have a raspberry with me to test this..)

Code: Select all

from subprocess import check_output
wifi_ip = check_output(['hostname', '-I'])
if wifi_ip is not None:
    # do stuff...
^ as i recall if nothing is connected the output is nothing, but if it does return something you could always print the output then change None for what ever print returned.

Re: Check wi-fi status from python script

Posted: Tue Jan 31, 2017 11:20 pm
by scotty134
Thank you guys for reply!

I don't like idea with ping just because in case if I don't have connection then I will wait for some time before I will get timeout error.
I just was thinking maybe RPi supports some internal wifi library where I check my connection status. I don't tell that 'ping' is wrong way, but it's not the most correct way. I will keep think about PING as spare plan.I will test it, maybe with python it will work fine.
scruss, I'm agree with maybe it's good idea. I'm gonna try it.

Regards,
Scotty