我在使用一个函数时遇到了一些问题,该函数应该识别您的操作系统并将相应的 PATH 返回到该主机文件,以便程序可以读取该文件并向其添加更多行。当将函数调用到 open(( 语句中时,该问题依赖于它,因为它返回"类型错误:预期的 str、bytes 或 os。PathLike 对象,而不是 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:WindowsSystem32driversetchosts"
elif _platform == "win64":
return r"C:WindowsSystem32driversetchosts"
# Host Files PATH:
# windows_path = r"C:WindowsSystem32driversetchosts"
# 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
中,平台名称不正确(文档中的所有值(。"linux"没有大写字母,自Python 3.3以来,"linux2"不再存在。
我只写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:WindowsSystem32driversetchosts"
这可以用更pythonic的方式重写:
from sys import platform as _platform
PATH_FOR_PLATFORM = {
"linux": "/etc/hosts",
"darwin": "/etc/hosts",
"win32": r"C:WindowsSystem32driversetchosts"
}
temp_path = PATH_FOR_PLATFORM[_platform]
希望对您有所帮助。