tags:

views:

107

answers:

4

What is the right way to call an external command and collect its output in OCaml?

In Python, I can do something like this:

os.popen('cmd').read()

How I can get all of an external program's output in OCaml? Or, better, OCaml with Lwt?

Thanks.

+6  A: 

You want Unix.open_process_in, which is described on page 388 of the OCaml system manual, version 3.10.

Norman Ramsey
http://caml.inria.fr/pub/docs/manual-ocaml/libref/Unix.html#VALopen_process_in
newacct
+5  A: 

For Lwt,

val pread : ?env:string array -> command -> string Lwt.t

seems to be a good contender. Documentation here: http://ocsigen.org/docu/1.3.0/Lwt_process.html

small_duck
+1  A: 
let process_output_to_list2 = fun command -> 
  let chan = Unix.open_process_in command in
  let res = ref ([] : string list) in
  let rec process_otl_aux () =  
    let e = input_line chan in
    res := e::!res;
    process_otl_aux() in
  try process_otl_aux ()
  with End_of_file ->
    let stat = Unix.close_process_in chan in (List.rev !res,stat)
let cmd_to_list command =
  let (l,_) = process_output_to_list2 command in l
A: 

There are lots of examples on PLEAC.

Gaius