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

时间:2018-08-09 07:25:59

标签: python python-3.x error-handling

我正在尝试使用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)

当我使用hosts文件的副本时,代码工作正常,但是当我想在原始文件上使用它时,我必须以管理员身份运行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"

我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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

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

article可能有帮助