Skip to content

Instantly share code, notes, and snippets.

@rlm
Created August 8, 2010 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rlm/513950 to your computer and use it in GitHub Desktop.
Save rlm/513950 to your computer and use it in GitHub Desktop.
(ns rlm.shell-write
(:refer-clojure :exclude [spit] )
(:use [clojure.contrib duck-streams command-line str-utils shell-out repl-utils])
(:import (java.io File BufferedReader ByteArrayOutputStream InputStreamReader))
(:import (org.apache.commons.exec PumpStreamHandler DefaultExecutor ExecuteWatchdog CommandLine)))
(defn sw
"same as sh but uses apache-commons to actually execute the process,
and prints output as soon as the subprocess returns output. Prints all
errors and normal ouput"
[& commands+args]
(let [[commands {:keys [dir]}] (split-with string? commands+args)]
(let
[
parsed-commands (str (CommandLine/parse (apply str (interpose " " commands))))
process (if dir
(.exec (Runtime/getRuntime) parsed-commands
(into-array String "") (file-str dir))
(.exec (Runtime/getRuntime) parsed-commands))]
(let [reader
(BufferedReader.
(InputStreamReader. (.getInputStream process)))
error-reader
(BufferedReader.
(InputStreamReader. (.getErrorStream process)))]
;output from program
(loop []
(let [line (.readLine reader )]
(if (not (nil? line))
(do (println line) (recur)) nil)))
;errors from program
(let [err-str
(loop [errors ""]
(let [line (.readLine error-reader )]
(if (not (nil? line))
(recur (str errors line "\n"))
errors)))]
(if (> (.length err-str) 0)
(do
(println "******************** Error Stream ********************")
(println err-str)
(println "******************************************************"))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment