运行 bash 来自 ocaml 的脚本

Run bash script from ocaml

我认为我的意思在标题中。我试图搜索是否可以从 ocaml 运行 bash 脚本,例如 java 或 php 但我找不到。 我知道我们可以使用 ocaml 作为脚本语言,但这不是我想要的 Ocaml as a scripting language 也就是说

我认为您正在寻找的是 Sys 模块 (http://caml.inria.fr/pub/docs/manual-ocaml/libref/Sys.html)。

Sys.command 可能是一种实现您想要的方式。

如果这还不够,那么您可能想看看 Unix 提供的内容 (http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html)。

来自 Ocaml 文档:

val command : string -> int

因此,如果您想从 Ocaml 调用脚本,请执行以下操作:

let status = Sys.command "./myexecutable.sh" in
Printf.printf "status = %d\n" status

您可以随意使用退出代码执行您想要的操作。

如果您有兴趣收集 bash 脚本的输出,

let () =
  (* Just using pstree as an example, you can pick something else *)
  let ic = Unix.open_process_in "pstree" in
  let all_input = ref [] in
  try
    while true do
      all_input := input_line oc :: !all_input
    done
  with
    End_of_file ->
    (* Just an example, you can do something else here *)
    close_in ic;
    List.iter print_endline !all_input