gpt4 book ai didi

python - 访问系统文件时python中的权限错误

转载 作者:行者123 更新时间:2023-12-03 08:46:53 24 4
gpt4 key购买 nike

我正在尝试用python编写一个程序,该程序会在某些小时内阻止某些网站。为此,我必须在Windows中更改hosts文件。我使用了以下代码:

 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)

当我使用hosts文件的副本时,代码工作正常,但是当我想在原始文件上使用它时,我必须以管理员身份运行cmd并从那里打开程序,但是一旦到达代码的这一行:
with open(hosts_path, "r+") as file:

这是Tracback:
File "Blocker.py",line 11min <module>
with open(hosts_path, "r+") as file:
PermissionError:[Errno13]Permission denied:"C:\Windows\System32\Drivers\etc"

我该怎么办?

最佳答案

您正在使用Windows用户运行脚本,该用户无权打开原始文件(位于C:\ Windows \ System32 \ Drivers的文件)

您是否尝试向用户授予对该文件夹的权限?

如果您有权访问Admin用户,请在文件夹C:\ Windows \ System32 \ Drivers上向将运行Python脚本的用户授予权限。

这个article可能有帮助

关于python - 访问系统文件时python中的权限错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51761106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com