Skip to content

Instantly share code, notes, and snippets.

@rtacconi
Last active October 27, 2020 13:30
Show Gist options
  • Save rtacconi/8ac389e243e8bbf7a836844a3ec53f3d to your computer and use it in GitHub Desktop.
Save rtacconi/8ac389e243e8bbf7a836844a3ec53f3d to your computer and use it in GitHub Desktop.
Piping a subprocesses output directly to stdout (java/clojure)
; this is not async
(defn shell
[cmd]
(->> (.. Runtime getRuntime (exec cmd) getInputStream)
java.io.InputStreamReader.
java.io.BufferedReader.
line-seq
(map str)))
; or this is async, use this as script to test it:
$ cat dumb.sh
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Loop iteration $i"
sleep 2
done
;this is the function
(defn run-proc
[proc-name arg-string callback]
(let [pbuilder (ProcessBuilder. (into-array String [proc-name arg-string]))
process (.start pbuilder)]
(with-open [reader (clojure.java.io/reader (.getInputStream process))]
(loop []
(when-let [line (.readLine ^java.io.BufferedReader reader)]
(callback line)
(recur))))))
; Testing:
(run-proc "./dumb.sh" "" println)
About to start...
Loop iteration 1
Loop iteration 2
Loop iteration 3
Loop iteration 4
Loop iteration 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment