Version française
Home     About     Download     Resources     Contact us    
Browse thread
commands.getoutput () in ocaml?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Dave Benjamin <dave@r...>
Subject: Re: [Caml-list] commands.getoutput () in ocaml?
On Wed, 22 Aug 2007, Eric Cooper wrote:

> On Thu, Aug 23, 2007 at 12:35:14AM +0200, Olivier Andrieu wrote:
>> you could use Buffer.add_substring instead of add_string, that will
>> avoid an intermediate copy of the string
>
> And you can use Buffer.add_channel to avoid intermediate strings
> altogether (until the final Buffer.to_string).

I'm not quite sure how to do this, actually. Here's what I've got so far:

let read_process command =
   let buffer_size = 2048 in
   let buffer = Buffer.create buffer_size in
   let in_channel = Unix.open_process_in command in
   begin
     try
       while true do
         Buffer.add_channel buffer in_channel buffer_size;
       done
     with
       | End_of_file -> ()
       | e ->
           ignore (Unix.close_process_in in_channel);
           raise e;
   end;
   ignore (Unix.close_process_in in_channel);
   Buffer.contents buffer

However, this doesn't work unless I set buffer_size to 1. Otherwise, the 
End_of_file fires before all the data is read in, so I either get nothing 
or an incomplete result.

Any advice?

Thanks,
Dave