The poor man's way would be using polling with either a ping module
import ping, time
def found():
print("FOUND INTERNET! :)")
def lost():
print("LOST INTERNET! :(")
def wait_and_notify_connection(found, lost, already_found=False):
while True:
# Ping Google DNS Server (99.999% Uptime)
if ping.do_one('8.8.8.8', timeout=2, psize=64) is not None:
if not already_found:
found()
already_found = True
else:
if already_found:
lost()
already_found = False
time.sleep(1)
wait_and_notify_connection(found, lost)
Or a subprocess call
import subprocess, time
def found():
print("FOUND INTERNET! :)")
def lost():
print("LOST INTERNET! :(")
def ping(target):
return True if subprocess.call(['ping', '-c 1', target]) == 0 else False
def wait_and_notify_connection(found, lost, already_found=False):
while True:
# Ping Google DNS Server (99.999% Uptime)
# and check return code
if ping('8.8.8.8'):
if not already_found:
found()
already_found = True
else:
if already_found:
lost()
already_found = False
time.sleep(1)
wait_and_notify_connection(found, lost)
But as @Blender mentioned, D-Bus notification could work better. Something like NetworkManager D-Bus Python client and reading some specs could help.
You can use Python's threading interface for background polling as well