【问题标题】:Redirect standard output OCaml重定向标准输出 OCaml
【发布时间】:2013-10-22 20:38:47
【问题描述】:

如何在 OCaml 中重定向标准输出? 我试过Format.set_formatter_out_channel,但它似乎不起作用。当我之后使用 printf 时,文本仍然打印在屏幕上,而我创建的文件仍然是空的。

【问题讨论】:

    标签: ocaml redirectstandardoutput


    【解决方案1】:

    您的实验失败的原因是 Printf.printf 没有使用 Format 模块的输出通道。格式模块用于漂亮的打印,这是一项相当复杂的任务。 Printf.printf 函数将格式化数据写入标准输出(C 风格的 printf)。

    您真的想重定向标准输出,还是只想写入特定通道?要写入频道oc,您可以使用

    Printf.fprintf oc ...
    

    而不是

    Printf.printf ...
    

    进行重定向是另一回事。您可以使用Unix.dup2 来完成。下面是一个示例会话,展示了如何做到这一点:

    $ cat redirected
    cat: redirected: No such file or directory
    
    $ cat redir.ml
    let main () =
        let newstdout = open_out "redirected" in
        Unix.dup2 (Unix.descr_of_out_channel newstdout) Unix.stdout;
        Printf.printf "line of text\n";
        Printf.printf "second line of text\n"
    
    let () = main ()
    
    $ ocamlopt -o redir unix.cmxa redir.ml
    $ ./redir
    
    $ cat redirected
    line of text
    second line of text
    

    由于这是在 OCaml I/O 系统背后更改低级文件描述符,所以我会小心一点。作为一个快速的 hack,它太棒了——我已经做过很多次了。

    更新

    这是上述代码的一个版本,它临时重定向标准输出,然后将其放回原来的位置。

    $ cat redirected
    cat: redirected: No such file or directory
    $
    $ cat redir.ml
    let main () =
        let oldstdout = Unix.dup Unix.stdout in
        let newstdout = open_out "redirected" in
        Unix.dup2 (Unix.descr_of_out_channel newstdout) Unix.stdout;
        Printf.printf "line of text\n";
        Printf.printf "second line of text\n";
        flush stdout;
        Unix.dup2 oldstdout Unix.stdout;
        Printf.printf "third line of text\n";
        Printf.printf "fourth line of text\n"
    
    let () = main ()
    $
    $ ocamlopt -o redir unix.cmxa redir.ml
    $ ./redir
    third line of text
    fourth line of text
    $
    $ cat redirected
    line of text
    second line of text
    

    【讨论】:

    • 谢谢。我希望能够从标准输出切换到文件,而不必将所有 printfs 更改为 fprintfs。我想我很懒(当我可以找到并替换时——但我做了很多 printfs 并且不得不在参数中为每个函数提供输出通道......)。
    • @Sheeft 将 Printf.printf 改为 Format.printf 并享受新的超级大国 :-)
    • 您可以根据需要使用实际重定向。我会扩展我的答案。
    • 有没有一种简单的方法可以稍后回到标准输出?例如。如果我只想暂时重定向一个函数的输出,然后恢复正常操作。
    • 使用 Unix dup 来做这些事情并不难。我会更新我的答案。
    猜你喜欢
    • 2014-01-20
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多