Search code examples
pythonclojureruntime

Clojure create python runtime and execute task


I want to write a program in Clojure, which has Python runtime and takes a Python function code, and a list of arguments to this function from some client over sockets, then it adds this function to runtime, calls it with the arguments and returns the result to client.

I want to know how to:

  1. Create Python runtime in Clojure
  2. Send code in this runtime and get result in Clojure

Solution

  • You can use clojure.java.shell for this:

    (ns tst.clj.core
      (:require [clojure.java.shell :as shell]  ))
    (t/refer-tupelo)
    (t/print-versions)
    
    (println (shell/sh "python" "-c" "print (2 + 3)" ))
    
    ;=> {:exit 0, :out "5\n", :err ""}
    

    Update

    If you are worried about the overhead of firing up Python, it seems to be only about 6 ms:

    (time
      (let [sum-vec (for [i (range 100)]
                      (Integer/parseInt (str/trim (:out (shell/sh "python" "-c" (format "print (%d + 3)" i))))))
            cumsum  (reduce + sum-vec)
            ]
        (println :cumsum cumsum)))
    
    ;=> :cumsum 5250
    ;=> "Elapsed time: 638.612278 msecs"