这是用于网站阻塞的Python代码。我正在使用木星笔记本运行这段代码。当我运行这个程序时,我会得到错误名为PermissionError。
import datetime
import time
end_time=datetime.datetime(2022,9,22)
site_block=["www.wscubetech.com","www.facebook.com"]
host_path="C:/Windows/System32/drivers/etc/hosts"
redirect="127.0.0.1"
while True:
if datetime.datetime.now()<end_time:
print("Start Blocking..")
with open(host_path,"r+") as host_file:
content = host_file.read()
for website in site_block:
if website not in content:
host_file.write(redirect+" "+website+"\n")
else:
pass
else:
with open(host_path,"r+") as host_file:
content = host_file.readlines()
host_file.seek(0)
for lines in content:
if not any(website in lines for website in site_block):
host_file.write(lines)
host_file.truncate()
time.sleep(5)这是我在运行这个程序时遇到的错误:
PermissionError
Traceback (most recent call last)
Input In [15], in <cell line: 8>()
9 if datetime.datetime.now()<end_time:
10 print("Start Blocking..")
---> 11 with open(host_path,"r+") as host_file:
12 content = host_file.read()
13 for website in site_block:
PermissionError: [Errno 13] Permission denied: 'C:/Windows/System32/drivers/etc/hosts发布于 2022-09-22 05:49:57
拒绝权限仅仅意味着系统没有权限打开该文件夹的文件。
C:\Windows\System32\drivers\etc\hosts只能由管理员写。您应该在管理员模式下运行脚本。
编辑(23/09/2022 -注释):
I在管理员模式下运行您的代码,没有错误,也没有输出,但是文件被修改了(然后删除了两行):
我重写了测试代码。这里是一种不同的方法:
site_block = ["www.facebook.com", "www.stackoverflow.com"]
host_path = "C:/Windows/System32/drivers/etc/hosts"
redirect = "127.0.0.1"
with open(host_path, "r+") as host_file:
for website in filter(lambda website: website not in host_file.read(), site_block):
host_file.write(redirect + " " + website + "\n")
time.sleep(5)
with open(host_path, "r") as host_file:
lines = host_file.readlines()
with open(host_path, "w") as output:
for line in lines:
if not any(redirect + " " + website + "\n" == line for website in site_block):
output.write(line)提示:
运行代码。
发布于 2022-09-22 05:49:05
当您没有做某事的权限时,就会导致PermissionError。文件C:/Windows/System32 32/驱动器/etc/host受权限保护。这就是为什么你不能访问它。为什么不以管理员的身份运行它呢?
https://stackoverflow.com/questions/73809788
复制相似问题