Best way to check if there is internet?

Gisle Vanem gisle.vanem at gmail.com
Wed Feb 9 05:29:03 EST 2022


Abdur-Rahmaan Janhangeer wrote:

> It's a demo to get the idea behind, uses requests and the rich library.

I'd never heard of 'Rich'. But d/l it and playing
with it, I came up with this version with fat green
spinner-bar:

import requests
from rich.console import Console

def ensure_internet():
     console = Console()
     domains = [ "https://google.com",
                 "https://yahoo.com",
                 "https://bing.com",
                 "https://www.ecosia.org",
                 "https://www.wikipedia.org" ]
     results = []
     with console.status ("Checking internet ...", spinner="material") as c:
         for domain in domains:
             c._spinner.text = "Checking %-40s" % domain
             try:
                 requests.get(domain)
                 results.append(1)
             except Exception as e:
                 results.append(0)

     if not any(results):
        print("No internet connection")

ensure_internet()

-------------------

Rich' is IMO a pretty amazing package.

--gv


More information about the Python-list mailing list