kafka
kafka

Reputation: 949

Call a program written in python in a program written in Ocaml

I wanted to ask if you could call in a program written in Ocaml a program written in python , and if the answer is yes how do I do?

Upvotes: 3

Views: 987

Answers (6)

Niki Yoshiuchi
Niki Yoshiuchi

Reputation: 17551

What exactly are you intending to do? Do you want to run it and forget about it? Then do a fork/exec. Do you want run it and wait until it's finished but otherwise do nothing? Then use Sys.command. Do you want to read/write to it? Then uses Unix.open_process* (or Unix.create_process*).

For example, if I want to run ls and print out the results, I can do this:

let ls = Unix.open_process_in "ls"
try
  while true do
    Printf.printf "%s\n" (input_line ls)
  done
with End_of_file -> ()
Unix.close_process_in ls

Upvotes: 5

0xFF
0xFF

Reputation: 4178

If your program is an executable (otherwise you would compile it ;) ) you can use the Unix module as you use it in C, for example :

let program = "path_to_python_program_exe" in

match Unix.fork () with
    | 0 -> (try
          Unix.execvp program [|program; "any_more_args_here"|]
       with
          _ -> printf "%s" "error while execv\n"; exit (-1))
    | -1 -> printf "%s" "error accured on fork\n"
    | _ -> ignore (wait ()); printf "%s" "parent exit...\n"

When you compile, you use the unix.cma for the compiler: ocamlc unix.cma you_ml.ml

Upvotes: 2

sepp2k
sepp2k

Reputation: 370112

You can execute commands using Sys.command, so you can just do Sys.command "python foo.py", assuming python is in your path and foo.py is in the current directory.

Upvotes: 2

ChristopheD
ChristopheD

Reputation: 116137

Don't have any real life experience with this, but this sounds interesting (from the Integrating Python with other languages wiki):

Pycaml: write Python extension modules in OCaml (instead of C), and use Python code and native libraries from OCaml programs.

Upvotes: 2

Achim
Achim

Reputation: 15702

It depends on your exact requirements, but you can use pythons os.system() to execute an program in the same way you would call it from the command line. That should be a good starting point.

Upvotes: -1

nosklo
nosklo

Reputation: 222852

Looks like you can use the Shell library.

Upvotes: 1

Related Questions