我希望我的ocaml应用程序直接下载,解压缩(gzip),然后逐行处理生成的文本文件,而不使用临时文件和外部程序。
我查看的库是 cohttp , ocurl 和 camlzip 。不幸的是,我找不到让他们一起工作的好方法。
OCaml实现这一目标的方式是什么?
答案 0 :(得分:5)
您可以使用管道和线程使 ocurl 和 camlzip 一起工作。概念证明:
#use "topfind";;
#thread;;
#require "unix";;
#require "curl";;
#require "zip";;
let () = Curl.(global_init CURLINIT_GLOBALALL)
let download url oc =
let open Curl in
let h = init () in
setopt h (CURLOPT_URL url);
setopt h (CURLOPT_WRITEFUNCTION (fun x -> output_string oc x; String.length x));
perform h;
cleanup h
let read_line really_input =
let buf = Buffer.create 256 in
try
while true do
let x = " " in
let () = really_input x 0 1 in
if x = "\n" then raise Exit else Buffer.add_string buf x;
done;
assert false
with
| Exit -> Buffer.contents buf
| End_of_file -> if Buffer.length buf = 0 then raise End_of_file else Buffer.contents buf
let curl_gzip_iter f url =
let ic, oc = Unix.pipe () in
let ic = Unix.in_channel_of_descr ic and oc = Unix.out_channel_of_descr oc in
let t = Thread.create (fun () -> download url oc; close_out oc) () in
let zic = Gzip.open_in_chan ic in
let zii = Gzip.really_input zic in
let () =
try
while true do
let () = f (read_line zii) in ()
done;
assert false
with
| End_of_file -> ()
in
Gzip.close_in zic;
Thread.join t
let () = curl_gzip_iter print_endline "file:///tmp/toto.gz"
但是,当必须处理错误时会很痛苦。
答案 1 :(得分:0)
如果您想完成工作,我会放弃“无外部程序”要求并编写 OCaml 源代码文件 download_gunzip_lines.ml
:
open Printf
let read_all_lines ic =
Seq.unfold (fun () -> try Some(input_line ic, ()) with _ -> None) ()
let () =
match Sys.argv with
| [|_; url|] ->
read_all_lines(Unix.open_process_in(sprintf "wget -q -O - %s | gunzip" url))
|> Seq.iter (fun line -> printf "%d\n" (String.length line))
| _ -> eprintf "Usage: download_gunzip_lines <url>"
使用 dune
文件:
(executable
(name download_gunzip_lines)
(libraries unix))
那么:
dune build --profile release
构建它并:
./_build/default/download_gunzip_lines.exe http://www.o-bible.com/download/kjv.gz
在国王詹姆斯圣经的副本上运行它。
更好的是,使用 Bash 脚本中的 OCaml 代码运行 wget
和 gunzip
,然后只处理 OCaml 中的行。