【问题标题】:permission error in python while accessing system files访问系统文件时python中的权限错误
【发布时间】: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


【解决方案1】:

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

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

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

这个article 可能会有所帮助

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 2023-04-10
    • 2011-07-23
    • 2015-10-18
    • 2011-06-29
    • 2017-03-23
    • 2011-10-29
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多