【发布时间】:2021-08-03 17:26:37
【问题描述】:
我最近创建了一个 python 项目,它通过在主机文件中进行更改来阻止 Youtube URL。我还使用任务计划程序在我打开电脑时自动运行程序。
问题:
所以我希望在这里做的是实现一个功能,在特定时间段后自动取消对 Youtube 的限制,比如晚上 9 点之后。我已经为此目的准备了一个“if-else”(我的代码上的注释部分),但没有使用它,因为我不知道该怎么做。我想过使用像“datetime”这样的模块,但不知道如何在这里准确地实现它。下面是代码:
#Using task Scheduler to automatically enable the programme on the startup of my computer
#import datetime
sites_to_block = ["www.youtube.com"]
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = "127.0.0.1"
def block():
#if datetime.now() < end_time:
print("block sites")
with open(hosts_path , 'r+') as hostsfile:
hosts_content = hostsfile.read()
for site in sites_to_block:
if site not in hosts_content:
hostsfile.write(redirect + " " + site + "\n")
#The following will be the code after the blocktime specified by the user is over.
'''else:
print('unblock sites')
with open(hosts_path,'r+') as hostsfile:
lines = hostsfile.readlines()
hostsfile.seek(0)
for line in lines:
if not any(site in line for site in sites_to_block):
hostsfile.write(line)
hostsfile.truncate()
'''
if __name__ == "__main__":
block()
在使用 datetime 模块时,我没有很好的经验。如果我们可以使用日期时间来实现,请告诉我该怎么做。否则,如果您知道,请分享使用其他模块的其他方式。
谢谢你,我真的很感谢你阅读这篇文章:)
【问题讨论】:
标签: python datetime time module