使用 Python 的主机文件注入器

Host file injector with Python

我在使用一个函数时遇到了一些问题,该函数应该识别您的操作系统和 return 该主机文件的相应路径,以便程序可以读取该文件并向其添加更多行。问题在于将函数调用到 open() 语句中,因为它 returns "TypeError: expected str, bytes or os.PathLike object, not NoneType"。这是我的代码:

import time
import os 
import platform
from datetime import datetime as dt
from sys import platform as _platform

def osFinder():
    if _platform == "Linux" or _platform == "Linux2":
        return "/etc/hosts"
    elif _platform == "darwin":
        return "/etc/hosts"
    elif _platform == "win32":
        return r"C:\Windows\System32\drivers\etc\hosts"
    elif _platform == "win64":
        return r"C:\Windows\System32\drivers\etc\hosts"

# Host Files PATH:
# windows_path = r"C:\Windows\System32\drivers\etc\hosts"
# unix_path = "/etc/hosts"
temp_path = osFinder()

redirect = "127.0.0.1"

sitesList = [
    "www.facebook.com",
    "www.netflix.com",
    "www.youtube.com"
]

from_hour = 7
to_hour = 16

while True:
    if dt(dt.now().year, dt.now().month, dt.now().day, from_hour) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, to_hour):
        print("Working")
        with open(temp_path, 'r+') as file:
            content = file.read()
            for site in sitesList:
                if site in content:
                    pass
                else:
                    file.write(redirect + " " + site + "\n")
    else:
        print("Happy Streaming")
        with open(temp_path, 'r+') as file:
            content = file.readlines()
            file.seek(0)
            for line in content:
                if not any(site in line for site in sitesList):
                    file.write(line)
            file.truncate()
    time.sleep(1)

osFinder 中,平台名称不正确 (all values in the doc)。 "linux" 没有资本,并且 "linux2" 自 Python 3.3.

以来不再存在

我刚写了 osFinder:

from sys import platform as _platform


def osFinder():
    if _platform == "linux":
        return "/etc/hosts"
    elif _platform == "darwin":
        return "/etc/hosts"
    elif _platform == "win32":
        return r"C:\Windows\System32\drivers\etc\hosts"

这可以用更 pythonic 的方式重写:

from sys import platform as _platform


PATH_FOR_PLATFORM = {
    "linux": "/etc/hosts", 
    "darwin": "/etc/hosts",
    "win32": r"C:\Windows\System32\drivers\etc\hosts"
}
temp_path = PATH_FOR_PLATFORM[_platform]

希望对您有所帮助。