所以尝试以管理员身份运行此python代码时遇到问题,因此我无法访问主机文件并在主机文件上写入。谁能帮我?我浏览了许多其他问题,但似乎没有一个起作用。
主机文件目录: C:\ Windows \ System32 \ Drivers \ etc \ hosts
(例如) Request UAC elevation from within a Python script?
其中一些答案实际上在提示获得管理员访问权限时起作用,但仍未授予我的程序许可。我发现的唯一方法是先以管理员身份运行python shell,然后以管理员身份运行代码或运行命令提示符,然后使用命令提示符打开python文件。
网站
https://boostlog.io/@faisalnad/create-a-website-blocker-with-python-5afe86ff47018500491f4898
该程序是用于阻止网站的。
import time
from datetime import datetime as dt
# change hosts path according to your OS
hosts_path = r”C:\Windows\System32\Drivers\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)
这是错误:
Working hours...
Traceback (most recent call last):
File "C:\Users\Key\Desktop\random project.py", line 19, in <module>
with open(hosts_path, 'r+') as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\Drivers\\etc\\hosts'