python - 无意的无限循环

标签 python infinite-loop

我刚刚开始使用 Python,在尝试 Ardit Suice 类(class)中的练习时,我编写了以下代码来实现自定义网站拦截器:

#!/usr/bin/env python3
import time
import os
from datetime import datetime as dt
hosts_path = '/etc/hosts'
tmp_path = '/tmp/hosts.tmp'
site_list = [ 'www.facebook.com', 'mail.google.com']

def write_hosts():
    hostfile = open(hosts_path, 'r')
    filecont = hostfile.read()
    hostfile.close
    for site in site_list:
        if not site in filecont:
            try:
                with open(hosts_path, 'a') as fh:
                    fh.write('127.0.1.1 ' + site + '\n')
                    print ("Wrote %s to hosts file %s" % (site, hosts_path))
            except PermissionError:
                print ("Sorry, you need to be admin to do this")

def write_fresh_hosts():
    testfile = open(tmp_path, 'w')
    hostfile = open(hosts_path, 'r')
    line=hostfile.readline()
    while line:
        for site in site_list:
            if not site in line:
                testfile.write(line)
            else:
                print ("Deleting %s from our blocked list" % site)
        line=hostfile.readline()

    testfile.close
    hostfile.close
    os.rename(tmp_path, hosts_path)

while True:
    print(1)
    print (dt.now())
    upper=dt(dt.now().year, dt.now().month, dt.now().day, 20, 0)
    lower=dt(dt.now().year, dt.now().month, dt.now().day, 17, 0)
    if lower <= dt.now() <= upper:
        print ("Blocking now")
        write_hosts()
        time.sleep(5)
    else:
        print ("Checking website lists for already blocked sites:")
        write_fresh_hosts()
        time.sleep(5)

我想做的是在指定的时间间隔内将站点列表写入主机文件,如果时间超出这些时间,则删除这些行。

但是我发现我的 hosts 文件很快就增长到 110MB,而且它只包含 127.0.0.1 localhost 这一行一遍又一遍地重复:

127.0.0.1       localhost
127.0.0.1       localhost
127.0.0.1       localhost
127.0.0.1       localhost
... (repeated)

在我的文件末尾,我发现了以下几行:

127.0.1.1   www.facebook.com
127.0.1.1   mail.google.com

最初 hosts 文件只包含一行:

127.0.0.1       localhost

输出:

sudo python siteblocker.py 
Checking website lists for already blocked sites:
Checking website lists for already blocked sites:
... (repeated)

我哪里出错了?

最佳答案

在这部分代码中:

while line:
    for site in site_list:
        if not site in line:
            testfile.write(line)
        else:
            print ("Deleting %s from our blocked list" % site)
    line=hostfile.readline()

您正在为主机文件的每一行遍历 site_list。每次在 line 中找不到给定的 site 时,您正在编写 line。由于您的 site_list 中有两个条目,而它们都不在您的 localhost 行中,因此您每行都写了两次。

由于您随后将新生成的输出文件作为新的输入文件,因此每次调用都有效地使文件中的行数加倍。

关于python - 无意的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49697006/

相关文章:

python - 将特定 URL 的正文响应保存到文件并使用 mitmproxy 对其进行解码

java - 什么会导致 Android Activity 无限循环?

python - 如何获得pandas数据框中k个连续行的总和?

python - 使用 SQLAlchemy 继承参数的 SQLite 和 Postgres 部分索引支持

c++ - C++中的cin缓冲区问题

c# - Unity C# 脚本 - 没有循环的无限循环......等等?

c - 在 C 编程中退出 while(1) 循环

python - 为什么我的代码没有结束

python - 注释相关模型中注释值的总和

python - 将 3D Matplot 保存为交互式 HTML