【问题标题】:How to Wait for more Content when Reading a File with Factor?读取带有因子的文件时如何等待更多内容?
【发布时间】:2015-11-05 09:29:40
【问题描述】:

我有类似下面的代码

"file.txt" utf8 <file-reader> [ [ print ] each-line ] with-input-stream* ;

这适用于file.txt 的当前内容,并且在到达文件结尾时结束处理(如本例中的打印)。但我希望进程等待附加到文件的新内容并处理它。或者换句话说,当前版本实现了Unixcat,但我希望它实现tail -f

我希望with-input-stream*(注意星号)能解决问题,因为文档说流最后没有关闭。但是我肯定还缺少其他东西。

【问题讨论】:

    标签: factor-lang


    【解决方案1】:

    你很幸运,我不久前写了一个这样的实用程序。见https://github.com/bjourne/playground-factor/wiki/Tips-and-Tricks-Filesystem#tailing-a-file

    USING: accessors io io.encodings.utf8 io.files io.monitors kernel namespaces ;
    IN: examples.files.tail
    
    : emit-changes ( monitor -- )
        dup next-change drop
        input-stream get output-stream get stream-copy* flush
        emit-changes ;
    
    : seek-input-end ( -- )
        0 seek-end input-stream get stream>> stream-seek ;
    
    : tail-file ( fname -- )
        [
            dup f <monitor> swap utf8 [
                seek-input-end emit-changes
            ] with-file-reader
        ] with-monitors ;
    

    我认为你的问题是给with-input-stream* 的引用会隐式关闭流(each-line 会这样做)。我不知道这是否是一个错误。像这样的词可以在不关闭的情况下读取完整的流:

    : my-stream-contents* ( stream -- seq )
        [ [ stream-read1 dup ] curry [ ] ] [ stream-exemplar produce-as nip ] bi ;
    

    然后:

    IN: scratchpad "/tmp/foo" utf8 <file-reader> [ my-stream-contents* print ] keep
    file contents here
    ...
    
    --- Data stack:
    T{ decoder f ~input-port~ utf8 f }
    IN: scratchpad my-stream-contents* print
    more file contents here
    ...
    

    【讨论】:

    • 太好了,谢谢。您的my-stream-contents* 方法立即奏效。我会尝试把它变成一个可行的脚本文件。不幸的是,我无法让tail-file 脚本工作。在 OSX 上它只是挂起,而在 Windows 上它会用“错误的参数”轰炸(正如你的 wiki 警告的那样)。我可能会带着新问题回来:-)。 - 顺便说一句:感谢您在 Factor 上工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多