python - 使用计时器逐行读取

标签 python multithreading python-2.7 timer readfile

我正在尝试使用txt文件中的python计时器按特定间隔读取每一行
但是它只读取第一行,并且连续显示

我的代码是

def read():
    try:
        while True:
            fo = open("foo.txt", "r")
            threading.Timer(1.0, read).start()
            line=fo.readline()
            print line
            if len(line)==0:
                break
    except:
        pass
read()

最佳答案

问题是您再次打开文件,该文件从第一行开始读取,并在读取该行后打印该文件,然后再次继续循环,这使循环成为无限循环。

另外,您对threading.Timer()的使用方式也不是您的用法,threading.Timer()在1秒钟后在新线程中启动read函数,一段时间后,您将有很多线程无限期地运行read()函数。

您可以通过使用threading.Timer()轻松地完成您想要做的事情(无需使用time.sleep()),以使程序休眠特定的秒数。例子 -

def read():
    import time
    with open("foo.txt", "r") as fo:
        for line in fo:
            print line
            time.sleep(1)
read()

如果您确实要使用threading.Timer(),则不需要while循环,您应该将文件对象作为参数传递给函数,例如-
def read(fo):
    line=fo.readline()
    print line
    if len(line) == 0:
        return
    t = threading.Timer(1.0, read, args=(fo,))
    t.start()
    t.join()

然后最初将函数调用为-
with open("foo.txt", "r") as fo:
    read(fo)

示例/演示-
>>> def a(x):
...     if  x >50:
...             return
...     print(x)
...     t = threading.Timer(1.0 , a, args=(x+1,))
...     t.start()
...     t.join()
...
>>> import threading
>>> a(1)
1
2
3
4
5
6
7
8

关于python - 使用计时器逐行读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890061/

相关文章:

multithreading - Erlang 实现的 Web 服务器的线程池模拟不起作用

没有 main 的 Python unittest 模块命令行参数

python - worker /时隙排列/约束过滤算法

Java 内存行为 : Different with Thread. sleep

python - (Python) 类型错误 : 'float' object is not subscriptable

java - 如何在 Future.cancel 之后取消生成的 Callable?

python - flask 的双向 ssl 身份验证

python - 在 Pandas 中用 Groupby 减去两列

Python/Pandas - 如何调整 auto_arima 模型参数以获得 future 预测

python - 多个枚举值的开关/大小写