从 OCaml 中的调用者捕获库的 printf 输出

Capturing a library's printf output from the caller in OCaml

我正在使用 ocaml-dns。

Here你可以看到它

 printf "retrying query for %d times\n%!" (4-count);

它使我的日志变得混乱!我已经在处理故障,我不关心那个输出,我想让它静音。如果不分叉和修改库本身,我该怎么做?我能以某种方式缓冲它的输出吗?

谢谢

如果您使用的是类 Unix 系统,您可以将标准输出重定向到“/dev/null”。这样的事情可能会奏效:

let nullout = open_out "/dev/null" in
Unix.dup2 (Unix.descr_of_out_channel nullout) Unix.stdout

这是一个显示它有效的会话(至少对我来说 OS X):

$ ocaml
        OCaml version 4.01.0

# #load "unix.cma";;
# Sys.system "echo unwanted message";;
Error: Unbound value Sys.system
# Sys.command "echo unwanted message";;
unwanted message
- : int = 0
# let nullout = open_out "/dev/null" in
  Unix.dup2 (Unix.descr_of_out_channel nullout) Unix.stdout;;
Sys.command "echo unwanted message";;
Sys.command "echo error message >&2";;
error message

如果你需要在其他时候使用标准输出,你的问题就更糟了。我认为,您可以通过 dup 的一些额外用途将 stdout 重定向回之前的位置。