我正在尝试用python编写一个程序,该程序在某些小时内阻止了一些网站。我使用了以下代码:
import time
from datetime import datetime as dt
hosts_path = "C:WindowsSystem32Driversetc"
redirect = "127.0.0.1"
weblist = ["www.youtube.com", "youtube.com", "www.zoomg.ir",
"zoomg.ir", "www.rooziato.com", "rooziato.com"]
while True:
if dt(dt.now().year, dt.now().month, dt.now().day,6) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, 20):
print("It's working hours")
with open(hosts_path, "r+") as file:
content = file.read()
for website in weblist:
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 weblist):
file.write(line)
file.truncate()
print("It's not working hours")
time.sleep(5)
当我使用主机文件的副本时,代码工作正常,但是当我想在原始文件上使用它时,我必须以管理员身份运行cmd并从那里打开程序。但是一旦它到达代码的这一行:
with open(hosts_path, "r+") as file:
这是回击:
File "Blocker.py",line 11min <module>
with open(hosts_path, "r+") as file:
PermissionError:[Errno13]Permission denied:"C:WindowsSystem32Driversetc"
我该怎么办?
您正在使用没有打开原始文件的权限的 Windows 用户运行脚本(文件位于 C:\Windows\System32\Drivers(
您是否尝试过向用户授予对该文件夹的权限?
如果您有权访问管理员用户,请在文件夹 C:\Windows\System32\Drivers 上向将运行 Python 脚本的用户授予权限
本文可能会有所帮助