使用Python复制“tail -f”

2024-06-12 21:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

根据David Beazley's talk on generators,以下代码应该复制UNIX tail -f命令:

import time
def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

f = open('followed.txt')
lines = follow(f)

for i in lines:
    print i

如果我在一个shell中运行这个,它在做“一些事情”,它确实锁定了IPython笔记本,但它不会打印跟踪.txt. 为什么?在


Tags: 代码命令txttimeonlineunixtail
2条回答

follow()生成器只返回在调用follow()之后写入文件的行。seek(0,2)将光标放在文件的结尾,然后尝试从该点开始读取新行。在

默认情况下,tail通常输出最后10行。如果你想要那样的东西

def follow(thefile):
    n_lines = 0
    # Seek to the end of the file
    thefile.seek(0,2)
    # Seek the cursor back one character at a time until you
    # reach the beginning of the file or 10 newlines are found.
    while n_lines < 10 and thefile.tell() > 0:
        # Go back one character and read it.
        thefile.seek(-1, 1)
        c = thefile.read(1)
        # Only go back 10 lines
        if c == '\n':
            n_lines += 1:
        # Reset the cursor position for the character we just read
        thefile.seek(-1, 1)

    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

我试过剧本,很管用。在

您必须确保您的输入文件是一个正在增长的文件。否则它将挂起并期待新的增长行。在

下面是一个脚本,在示例.csv每5秒。在

import os
import time
import datetime

while True:
    os.system("echo " + "sample line with timestamp:{0}".format(datetime.datetime.now()) + " >> " + " sample.csv")
    time.sleep(5)

{您将使用}来查看您的输出}。在

相关问题 更多 >