【问题标题】:Youtube BlockerYoutube 拦截器
【发布时间】: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


    【解决方案1】:

    你可以试试这样的:

    import datetime as dt
    
    # the blocked time intervals
    intervals = [
        [dt.time(hour=0), dt.time(hour=8)],
        [dt.time(hour=21), dt.time(hour=0)],
    ]
    
    # check if a pobe time is in an interval
    def is_in_interval(start: dt.time, stop: dt.time, probe: dt.time) -> bool:
        if start < stop:
            return bool(start <= probe and probe < stop)
        
        elif stop < start:
            return bool(start <= probe or probe < stop)
    
        raise Exception("start and stop are equal")  # create your own exception
        
    current_time = dt.datetime.now().time()
    for interval in intervals:
        print(is_in_interval(interval[0], interval[1], current_time))
    

    【讨论】:

    • 嘿感谢您的解决方案,现在才看到。这里的探测时间到底是多少?您有空时能否通过解决方案中的 cmets 进行解释?您的解决方案看起来很有说服力。如果您能通过编辑和放置 cmets 来解释它,我将不胜感激。谢谢@jpotyka
    • 正如您在解决方案的下部看到的,探测时间用于由 current_time 设置。这意味着探测参数是在阻塞间隔中应该检查的时间。或者换句话说,检查 current_time 是否在阻塞间隔内。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2014-03-10
    • 2013-06-25
    • 2018-08-09
    • 2023-03-13
    • 2016-09-10
    • 2020-06-17
    相关资源
    最近更新 更多