我正在Python中做一个练习,其中包括编写一个程序,该程序通过在主机文件中添加或隐藏站点列表来在特定时间阻止某些站点。该程序每隔5秒运行一次。阻止部分正常工作,但是当我想取消阻止站点时,它需要花费更多时间才能取消阻止站点。
这是代码:
import time
hosts_path=r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp="hosts"
redirect="127.0.0.1"
website_list=["www.facebook.com","www.gmail.com",r"https://mail.google.com/","https://www.youtube.com/","https://www.helsebiblioteket.no/om-oss/english?emneside=true"]
while True:
if 2200 >= int(time.strftime("%H%M")) >= 2100:
print("a")
with open(hosts_path,'r+') as hosts:
content=hosts.read()
for website in website_list:
if website in content:
pass
else:
hosts.write('\n'+redirect+ ' '+ website+ '\n')
**else:
print('b')
with open(hosts_path,'r+') as hosts:
lines=hosts.readlines()
hosts.seek(0)
for l in lines:
if "#" not in l:
del lines[lines.index(l)]
with open(hosts_path,'w') as hosts:
for line in lines:
hosts.write(line)**
time.sleep(5)
粗体字是代码中有问题的部分。程序将覆盖文件而未完成所有循环。例如,我有三个要删除的站点。勾选1次后,只会删除1个站点。