Python Automation Project: Build a ‘Focus Mode’ Website Blocker

3D visualization of a digital shield blocking social media icons from a browser, representing a Python website blocker project.

This script redirects distracting websites to your computer’s “localhost” (a blank page), helping you focus. The Python Website Blocker is a simple tool designed to make blocking unwanted sites easy and effective.

⚠️ WARNING: THIS IS AN ADVANCED SCRIPT

  • This script edits a system file. You must run it as an Administrator (or with sudo).
  • A mistake can temporarily mess up your internet access. Be careful!

The hosts File

On Windows, Mac, and Linux, there’s a file called hosts that maps domain names to IP addresses.

The Script

import time

# Use the correct path for your OS

REDIRECT_IP = "127.0.0.1"
SITES_TO_BLOCK = [
    "www.reddit.com",
    "reddit.com",
    "www.facebook.com",
    "facebook.com"
]

def block_sites():
    print("Focus Mode ON. Run as Administrator!")
    try:
        with open(HOSTS_PATH, 'r+') as f:
            content = f.read()
            for site in SITES_TO_BLOCK:
                if site not in content:
                    f.write(f"{REDIRECT_IP} {site}\n")
        print("Websites blocked.")
    except PermissionError:
        print("Error: Please run this script as an Administrator (or with sudo).")
    except Exception as e:
        print(f"An error occurred: {e}")

# Call the function to block sites
block_sites()

Challenge: Can you write an unblock_sites() function that reads the file, finds the lines with those sites, and removes them?

Similar Posts

Leave a Reply