网站拦截器在停止进程后继续阻止网站
Website blocker continues to block websites after stopping process
我编写了一个可以阻止某些网站的网站拦截器。一旦我 运行 脚本,网站就会被阻止。我面临的问题是,尽管停止了该过程,但我仍然无法访问网站。换句话说,我终止程序后网站仍然被阻止。这是我的代码:
import time
import os
os.chdir("C:/Windows/System32/drivers/etc/")
file = open('hosts', 'w')
hosts_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
website_blocked = ["www.facebook.com", "facebook.com", "www.twitter.com", "twitter.com", "www.instagram.com"
, "instagram.com"]
while True:
if 1 == 1:
print("Working Blocked")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_blocked:
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_blocked):
file.write(line)
file.truncate()
print("Website Allowed")
time.sleep(5)
我想知道如何让网站拦截器在进程停止后停止拦截网站。
您可以使用 atexit 将清理功能添加到您的脚本中,以取消阻止网站。
def unblock(hosts_path,website_blocked):
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_blocked):
file.write(line)
file.truncate()
import atexit
atexit.register(unblock, hosts_path, website_blocked)
我编写了一个可以阻止某些网站的网站拦截器。一旦我 运行 脚本,网站就会被阻止。我面临的问题是,尽管停止了该过程,但我仍然无法访问网站。换句话说,我终止程序后网站仍然被阻止。这是我的代码:
import time
import os
os.chdir("C:/Windows/System32/drivers/etc/")
file = open('hosts', 'w')
hosts_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
website_blocked = ["www.facebook.com", "facebook.com", "www.twitter.com", "twitter.com", "www.instagram.com"
, "instagram.com"]
while True:
if 1 == 1:
print("Working Blocked")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_blocked:
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_blocked):
file.write(line)
file.truncate()
print("Website Allowed")
time.sleep(5)
我想知道如何让网站拦截器在进程停止后停止拦截网站。
您可以使用 atexit 将清理功能添加到您的脚本中,以取消阻止网站。
def unblock(hosts_path,website_blocked):
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_blocked):
file.write(line)
file.truncate()
import atexit
atexit.register(unblock, hosts_path, website_blocked)