unix 使用OCaml收集外部命令的输出

5jvtdoz2  于 2023-03-29  发布在  Unix
关注(0)|答案(5)|浏览(150)

在OCaml中调用外部命令并收集其输出的正确方法是什么?
在Python中,我可以这样做:

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

如何在OCaml中获取所有外部程序的输出?或者,更好的是,OCaml与Lwt?
谢谢。

ejk8hzay

ejk8hzay1#

您需要Unix.open_process_in,这在OCaml系统手册3.10版的第388页有描述。

ifmq2ha2

ifmq2ha22#

对于Lwt,
瓦尔pread:?env:string array -〉command -〉string Lwt.t
似乎是一个很好的竞争者。文档在这里:http://ocsigen.org/docu/1.3.0/Lwt_process.html

tf7tbtn2

tf7tbtn23#

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
yk9xbfzb

yk9xbfzb4#

您可以使用第三方库Rashell,该库使用Lwt定义一些高级原语来读取进程的输出。这些原语在Rashell_Command模块中定义,包括:

  • exec_utility将进程的输出作为字符串读取;
  • exec_test只读取进程的退出状态;
  • exec_query逐行读取进程的输出作为string Lwt_stream.t
  • exec_filter使用外部程序作为string Lwt_stream.t -> string Lwt_stream.t转换。

command函数用于创建命令上下文,可以在其上应用前面的原语,它具有签名:

val command : ?workdir:string -> ?env:string array -> string * (string array) -> t
(** [command (program, argv)] prepare a command description with the
    given [program] and argument vector [argv]. *)

比如说

Rashell_Command.(exec_utility ~chomp:true (command("", [| "uname" |])))

是一个string Lwt.t,它返回“uname”命令的“chomped”字符串(删除了新的一行)。

Rashell_Command.(exec_query (command("", [| "find"; "/home/user"; "-type"; "f"; "-name"; "*.orig" |])))

是一个string Lwt_stream.t,其元素是通过命令找到的文件的路径

find /home/user -type f -name '*.orig'

Rashell库还定义了一些常用命令的接口,Rashell_Posix中定义了一个很好的find命令接口--顺便说一下,这保证了POSIX的可移植性。

ijxebb2r

ijxebb2r5#

安装电池,然后将其作为库,然后:

BatUnix.run_and_read 'cmd'

其接口为:

val BatUnix.run_and_read string -> BatUnix.process_status * string

相关问题