view src/rlm/shell_write.clj @ 0:78a630e650d2

initial import
author Robert McIntyre <rlm@mit.edu>
date Tue, 18 Oct 2011 00:57:08 -0700
parents
children
line wrap: on
line source
1 (ns rlm.shell-write
3 (:use
4 [clojure.contrib
5 [duck-streams :only [file-str]]
6 command-line
7 str-utils
8 shell-out
9 ])
11 (:import (java.io File BufferedReader ByteArrayOutputStream InputStreamReader))
12 (:import (org.apache.commons.exec PumpStreamHandler DefaultExecutor ExecuteWatchdog CommandLine)))
15 (defn sw
16 "same as sh but uses apache-commons to actually execute the process,
17 and prints output as soon as the subprocess returns output. Prints all
18 errors and normal ouput"
19 [& commands+args]
21 (let [[commands {:keys [dir]}] (split-with string? commands+args)]
22 (let
23 [
24 parsed-commands (str (CommandLine/parse (apply str (interpose " " commands))))
25 process (if dir
26 (.exec (Runtime/getRuntime) parsed-commands
27 (into-array String "") (file-str dir))
28 (.exec (Runtime/getRuntime) parsed-commands))]
29 (println parsed-commands)
30 (let [reader
31 (BufferedReader.
32 (InputStreamReader. (.getInputStream process)))
34 error-reader
35 (BufferedReader.
36 (InputStreamReader. (.getErrorStream process)))]
38 ;output from program
40 (loop []
41 (let [line (.readLine reader )]
42 (if (not (nil? line))
43 (do (println line) (recur)) nil)))
45 ;errors from program
48 (let [err-str
50 (loop [errors ""]
51 (let [line (.readLine error-reader )]
52 (if (not (nil? line))
53 (recur (str errors line "\n"))
54 errors)))]
55 (if (> (.length err-str) 0)
56 (do
57 (println "******************** Error Stream ********************")
58 (println err-str)
59 (println "******************************************************"))))))))