scotty134
Posts: 2
Joined: Sat Jan 28, 2017 7:21 pm

Check wi-fi status from python script

Tue Jan 31, 2017 2:33 pm

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

User avatar
scruss
Posts: 3212
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Check wi-fi status from python script

Tue Jan 31, 2017 4:53 pm

Maybe parse the output from the ifconfig wlan0 command? That will tell you if it's up, and has an IP address.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

stderr
Posts: 2178
Joined: Sat Dec 01, 2012 11:29 pm

Re: Check wi-fi status from python script

Tue Jan 31, 2017 5:44 pm

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.

Davies
Posts: 150
Joined: Sat Apr 04, 2015 4:24 pm

Re: Check wi-fi status from python script

Tue Jan 31, 2017 6:49 pm

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.

scotty134
Posts: 2
Joined: Sat Jan 28, 2017 7:21 pm

Re: Check wi-fi status from python script

Tue Jan 31, 2017 11:20 pm

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

Return to “Python”