In this post we are going to write a Python code that blocks certain website which distract us from our goals.

Requirement

What we are going to in this program is that we will pass the link of websites which you think is distracting and the time that you are working on your computer and program will block those website.

Program Architecture:

Every system have host file whether it is Mac, Windows or Linux.
Host file in Mac and Linux :

/etc/hosts

Host file in Windows:

C:\Windows\System32\drivers\etc

Working of host file: Host is an operating system file which maps hostnames to IP addresses. In this program we will be mapping hostnames of websites to our localhost address. Using python file handling manipulation we will write the hostname in hosts.txt and remove the lines after your working hours.

Host file in windows looks like this

# Run this script as root

import time
from datetime import datetime as dt

# change hosts path according to your OS
hosts_path = "/etc/hosts"
# localhost's IP
redirect = "127.0.0.1"

# websites That you want to block
website_list =
["www.facebook.com","facebook.com",
	"dub119.mail.live.com","www.dub119.mail.live.com",
	"www.gmail.com","gmail.com"]

while True:

	# time of your work
	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:
					# mapping hostnames to your localhost IP address
					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)

			# removing hostnmes from host file
			file.truncate()

		print("Fun hours...")
	time.sleep(5)

Special Note

Run your Python IDE as administrator as you(Current User) might not have permission to access to hosts file.

For more Python related blogs Visit Us Geekycodes . Follow us on Instagram.

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com

Leave a Reply