简体   繁体   中英

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM