所以我有一个 .pyw 文件,打开它的默认程序是 pythonw.exe,但是当我运行它时,它会打开 Visual Studio。也许是幕后错误?程序是在任务调度程序中设置的,具有访问 Windows 中主机文件的最高权限。测试路径工作正常。
import time
from datetime import datetime as dt
# Temporary hosts path to test
hosts_temp = r"C:\Users\letto4135\Desktop\python_programs\web_block\hosts"
# Hosts path in windows
hosts_path = r'C:\Windows\System32\drivers\etc\hosts'
# Redirect to this IP
redirect = "127.0.0.1"
# List of Websites to block
website_list = ['www.facebook.com','facebook.com']
while True:
# If between time, block sites
if dt(dt.now().year,dt.now().month,dt.now().day,8) < dt.now() < dt(dt.now().year, dt.now().month,dt.now().day,16):
with open(hosts_path,'r+') as file:
content = file.read()
for site in website_list:
if site in content:
pass
else:
file.write('\n' + redirect + ' ' + site)
# If not between time allow sites
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 website_list):
file.write(line)
file.truncate()
# Run every ("") seconds.
time.sleep(5)