python
  1. python-introduction-pythonweb-blocker

Python Web Blocker

Syntax

import time
from datetime import datetime as dt

hosts_temp = "hosts"
hosts_path = "/etc/hosts"
redirect = "127.0.0.1"
website_list = ["www.facebook.com", "facebook.com", "www.instagram.com", "instagram.com", "www.twitter.com", "twitter.com"]

while True:
    if dt(dt.now().year, dt.now().month, dt.now().day, 8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 16):
        print("Working hours...")
        with open(hosts_path, 'r+') as file:
            content = file.read()
            for website in website_list:
                if website in content:
                    pass
                else:
                    file.write(redirect + " " + website + "\n")
    else:
        with open(hosts_path, 'r+') as file:
            content = file.readlines()
            file.seek(0)
            for line in content:
                if not any(website in line for website in website_list):
                    file.write(line)
            file.truncate()
        print("Fun hours...")
    time.sleep(5)

Example

Blocking social media websites during working hours to improve productivity.

Output

The program will block the specified websites during working hours, and unblock them during off-time.

Explanation

The Python Web Blocker is a tool to help improve productivity during work hours by blocking distracting websites. By adding websites to the website_list variable, they will be blocked during working hours specified in the if statement. The tool works by modifying the "hosts" file on the local machine to redirect traffic from the specified website to the loopback address of the machine (127.0.0.1).

Use

The Python Web Blocker is a useful tool for improving productivity during working hours. It is designed for personal use and can be customized to block specific websites during specific times.

Important Points

  • The Python Web Blocker modifies the "hosts" file on the local machine. This requires administrator privileges to run.
  • The program is a simple script and has limited functionality beyond blocking websites during specified hours.

Summary

The Python Web Blocker is a simple tool for blocking websites during working hours, designed to improve productivity. It can be customized to block specific websites during specific times.

Published on: