Hi, i need a simple python code which would trigger a command if there is an internet connection; if there isn't, sleep for some time and check again until there is.
I found few examples, but they're all rather difficult to grasp and being new to python, I can't get them working. If there really is no simple solution for this in Python, i'll try and go with the other ones. Thanks!

Dani AI

Generated

New Python-friendly way to do this without a flag variable and with fewer false negatives. As suggested, prefer a while True loop with break. Also use a short timeout so your script does not hang, and probe more than one target so a single host outage does not look like your internet is down. The first check below avoids DNS entirely by opening a TCP socket to a public resolver; the second uses a lightweight HTTP HEAD request.

import time
import socket
import urllib.request
import urllib.error

TEST_URLS = (
    "https://www.gstatic.com/generate_204",  # returns 204 when online
    "https://www.google.com",                # fallback
)

def is_online(timeout=3.0) -> bool:
    # 1) Fast IP-level check (no DNS). Some networks may block this; ignore failures.
    try:
        socket.create_connection(("1.1.1.1", 53), timeout=timeout).close()
        return True
    except OSError:
        pass
    # 2) HTTP check with minimal data transfer.
    for url in TEST_URLS:
        try:
            req = urllib.request.Request(url, method="HEAD")
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                code = resp.getcode()
                if 200 <= code < 400:
                    return True
        except (urllib.error.URLError, socket.timeout):
            continue
    return False

def wait_for_internet(pause=5, max_wait=None):
    start = time.time()
    while True:
        if is_online():
            break
        if max_wait and (time.time() - start) > max_wait:
            raise TimeoutError("Gave up waiting for internet connectivity.")
        time.sleep(pause)

# Example:
# wait_for_internet(pause=5)
# run_your_command_here()

Notes:

  • Use except ... as e only if you log or inspect e; otherwise skip binding.
  • If you are behind a captive portal, the generate_204 URL will usually not return 204/200; treat that as not online until the portal is cleared.
  • Consider exponential backoff (e.g., min(60, 2**attempt)) if this runs long-lived.

Recommended Answers

All 8 Replies

I would just try to open any sure to be up url in try statement inside while True loop. In else statement of try I would put activity for internet open. Most likely a function call.

Ok, i've managed to get this far:

#!/usr/bin/env python2
import urllib2 
import time

f = open("/home/laur/.conky/data_file.dat", "w")
loop_value = 1

while (loop_value = 1):
try:
        urllib2.urlopen("http://google.com")
except urllib2.URLError, e:
	f.write( "Network currently down." )
	time.sleep( 5 )
else:
	f.write( "Up and running." )
	loop_value = 0

Other commads to run placed here.

Yet i get an error:

while (loop_value = 1):
                      ^
SyntaxError: invalid syntax

Is the 'loop_value' incorrectly defined?

You can not put assignment as while condition.

Any hints perhaps?:D
Can't get any methods error-free nor working.

That is not Python, it is shell script.

You must use comparision operator ==

That is not Python, it is shell script.
You must use comparision operator ==

Thank you! That was it.

For future searchers:

#!/usr/bin/python
import urllib2 
import time

loop_value = 1

while (loop_value == 1):
    try:
	urllib2.urlopen("http://www.google.com")
    except urllib2.URLError, e:
	time.sleep( 10 )
    else:
	loop_value = 0
	<commands to be ran when internet connection is established go here>

Little docstring would be nice to catch the logic easier, like: """ Wait for connection to Internet to be established and do commands, then exit """. Good effort even my version would drop the flag variable and instead use break from end of else branch and while True: loop. I would not also put ', e' in except line as e is not used, also modern syntax is 'as e'

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.