【发布时间】:2018-08-09 07:25:59
【问题描述】:
我正在尝试使用 python 编写一个程序,该程序会在特定时间阻止某些网站。为此,我必须更改 windows 中的主机文件。我使用了以下代码:
import time
from datetime import datetime as dt
hosts_path = "C:\Windows\System32\Drivers\etc"
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:\Windows\System32\Drivers\etc"
我该怎么办?
【问题讨论】:
-
似乎不是特定于 python 的问题。我敢打赌,你可以用 .bat 文件重现它。你能告诉我们追溯吗?
-
您无权访问此文件。尝试以管理员身份运行 shell。然后从中执行python脚本。
-
@Utsav 我以管理员身份运行 shell 并出现了该错误
-
@FarzinNasiri 在代码格式中添加回溯到您的问题,而不是在评论中
-
您的
hosts路径不完整。它只会转到etc,这是一个目录。当然你不能打开那个
标签: python python-3.x error-handling