Distractions are everywhere online, making staying focused on important tasks difficult. Website blocker tools can help by restricting access to time-wasting sites.
This comprehensive guide will build a customizable website blocker in Python that gives you control over when and where to browse.
Introduction
The internet provides a massive amount of information and entertainment. But it also enables endless distractions that can derail productivity.
According to RescueTime, the average person spends over 2 hours per day on social media alone. Add in other sites like news, videos, and games - and those hours can climb higher.
This issue has led to the rise of website-blocking apps and extensions. By intentionally limiting access, you reduce the temptation to stray onto procrastination-inducing sites.
Popular existing options include:
Freedom - Blocks sites across devices for a monthly fee. Allows scheduled sessions.
ColdTurkey - Blocks sites based on a countdown timer. Paid versions add more options.
StayFocusd - Chrome extension to block sites for set periods of time.
BlockSite - A browser extension for blocking sites on a schedule. Free and paid tiers.
While these work, they also have limitations:
Recurring subscriptions and fees
Restricted site customization
Limited to specific browsers
Can't easily undo blocks during sessions
By building our own website blocker in Python, we can create a free, cross-platform tool with more flexibility:
Block any sites we want
Set specific blocking periods
Easily unblock sites when needed
Works on all major operating systems
In the rest of this guide, we will walk through the key steps to create an effective website-blocking program with Python.
Overview of How the Website Blocker Works
Before jumping into the code, let's briefly summarize how the website blocker will function:
User inputs list of sites they want to block
The user sets start and end times for blocking periods
The program checks the current time against blocking times in a loop
If, within a blocking period, the program edits the system host file to block target sites
Host file redirects blocked sites to 127.0.0.1 (localhost)
Users can exit the program to restore normal site access
Modifying the host file allows our program to block sites across all browsers and applications. And using Python gives us operating system portability.
To get started, fork the file and follow the guide.
Step 1 - Import Required Modules
Our website blocker will rely on 3 core modules in the Python standard library:
import time
from datetime import datetime as f
time - Provides functions like sleep() to pause the program for the given number of seconds. This allows repeating actions.
datetime - Gives useful classes for working with dates and times. We can easily get the current time, construct time objects, and format times.
These powerful built-in modules will handle most of the underlying logic for our program.
Step 2 - Get User Input for Sites to Block
First, we must let users specify which websites to block access to during focus sessions.
We can use Python's input() function to prompt the user and store their sites in a list:
host_temp = 'hosts' # to test the program as we need adminstartive privilage to run the host_path file
host_path = "/etc/hosts" #be careful and test with the host_temp file until you are ready to use this file.
redirect = '127.0.0.1' #we can creat a redirect to this site ot create a random page online to redirect the user to read
banned_list = ['www.facebook.com', 'facebook.com', 'x.com', 'www.twitter.com'] #pages i banned to give me access to focus
Breaking this down:
Redirect the URL to 127.0.0.1, which is the local host.
Save the list to global banned_sites that other functions can access
Now, we can get a custom list of distracting sites to block from the user when the program runs.
Step 3 - Get Blocking Period Times
In addition to blocking certain sites, we also want to let the user specify when those sites should be blocked.
A good approach is to have the user provide a start and end time for blocking periods. We'll use the 24-hour format to simplify timing logic later on.
Start Infinite Loop
We use a while True loop to run the code continuously:
while True:
This loop will run forever until the program is manually stopped.
Check Time
Inside the loop, we check the current time using the datetime library:
if f(f.now().year, f.now().month, f.now().day,8) < f.now() < f(f.now().year, f.now().month, f.now().day,13):
print('Working Hours')
This creates a datetime object for the current time and objects for 8 a.m. and 1 p.m. today. We compare the current time to see if it is between 8 a.m. and 13 p.m.
If it falls within this time frame, our programs print working hours and block the website from running.
for web_site in banned_list:
if web_site in content:
pass
else:
file.write(redirect+' '+ web_site+'\n ')
Next, we check for web_site in the banned_list and confirm line by line if any matches our content, and if it does, we pass; otherwise, we write the banned website in our list.
Working Hours
If it is between 8 am and 1 pm, we print a message and open the host file to modify it:
print('Working Hours')
with open(host_path, 'r+') as file:
content = file.read()
The file is opened for reading and writing.
with open(host_path, 'r+') as file:
content = file.read()
#print(content)
We loop through the banned sites:
file_contents = file.readlines()
for website in banned_list:
if website not in file_contents:
file.write(redirect + " " + website + "\n")
For each banned site, we check if it is already blocked in the host file. If not, we write a new line redirecting it to 127.0.0.1 to block it.
Fun Time
After 1 p.m., we enter the 'else' part of the code:
else:
print("Fun time! Allowing sites...")
with open(host_path, 'r+') as file:
We again open the host file for reading and writing.
This time, we remove the blocked sites:
file_contents = file.readlines()
file.seek(0)
for line in file_contents:
if not any(site in line for site in banned_list):
file.write(line)
We loop through the file lines and only write ones that don't contain the banned sites. This removes the blocked entries.
file.truncate()
Finally, we truncate the file to remove any leftover blank lines.
Delay and Repeat
After updating the host file, we delay for 10 seconds before repeating the loop:
time.sleep(10)
This continually checks the time and modifies the host file to block or allow sites accordingly.
And that covers this code in detail! It shows how Python can interact with the system and schedule tasks based on the time. The host file is modified dynamically to control website access.
Final Thoughts
And that covers the steps to build your own website blocker with Python!
Building projects like this is a great way to level up your Python skills. You get experience with timing events, terminal interaction, file I/O, system commands, and more.
If you like my work and want to help me continue dropping content like this, buy me a cup of coffee.
If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.