类似“tail -f”的生成器

我在 Python 中有这个方便的函数:


def follow(path):

    with open(self.path) as lines:

        lines.seek(0, 2)  # seek to EOF


        while True:

            line = lines.readline()

            if not line:

                time.sleep(0.1)

                    continue

                yield line 

它做一些类似于 UNIX 的事情tail -f:你得到文件的最后几行。这很方便,因为您可以在不阻塞的情况下获取生成器并将其传递给另一个函数。


然后我不得不在 Go 中做同样的事情。我是这门语言的新手,所以我不确定我所做的对于 Go 来说是否足够惯用/正确。


这是代码:


func Follow(fileName string) chan string {


    out_chan := make(chan string)


    file, err := os.Open(fileName)

    if err != nil {

        log.Fatal(err)

    }


    file.Seek(0, os.SEEK_END)

    bf := bufio.NewReader(file)


    go func() {

        for {

            line, _, _ := bf.ReadLine()


            if len(line) == 0 {

                time.Sleep(10 * time.Millisecond)

            } else {

                out_chan <- string(line)

            }

        }


        defer file.Close()

        close(out_chan)

    }()


    return out_chan

}

在 Go 中有没有更干净的方法来做到这一点?我有一种感觉,对这样的事情使用异步调用是一种矫枉过正,这真的让我很困扰。


慕仙森
浏览 162回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go