python - 网站拦截器在停止进程后继续阻止网站
问题描述
我编写了一个可以阻止某些网站的网站拦截器。一旦我运行脚本,网站就会被阻止。我面临的问题是,尽管停止了该过程,但我仍然无法访问这些网站。换句话说,我终止程序后网站仍然被阻止。这是我的代码:
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)
推荐阅读
- java - 复合设计模式能否避免使用集合(List、HashTable)数据结构?
- c# - 无限转轮 Unity2d
- css - 如何使用 css 使 2 个导航重叠
- angular - 当数据来自 API 时,如何设置 mat-select 的默认值?
- xamarin - 如何创建针对特定 android 版本的 xamarin android 项目?
- vbscript - VBscript 错误代码 800A0046 权限被拒绝
- python - 如何根据列值重复熊猫数据框记录
- typescript - 无法导入从 bazel 构建的打字稿模块
- typescript - Vue.js 生命周期事件以及从哪里开始加载商店属性 (Vue.observable)
- java - 扫描仪有问题