-1

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
KgOfHedgehogs
  • 377
  • 3
  • 16

1 Answers1

3

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"
Alan Thompson
  • 29,276
  • 6
  • 41
  • 48
  • So if I want to run function do multiple sets of arguments, I need start new Python interpreter for each set of arguments? It looks quite heavy – KgOfHedgehogs Feb 03 '17 at 19:49
  • 1
    You could start a python webservice and talk to it over http. Or you could make one big python program/script, run it, and save the results into a list or dict. – Alan Thompson Feb 03 '17 at 19:53
  • I think this is what I need. But why over http? May be I can simply organize this over tcp sockets? – KgOfHedgehogs Feb 03 '17 at 19:55
  • Let http take care of all the data formatting, transfer, and socket care & feeding (http does, after all, run over a tcp socket). It is a waste of time for you to worry about all of that low-level stuff (& even worse for you to re-create it from scratch!). – Alan Thompson Feb 05 '17 at 20:24