Clojure And STDERR

September 29, 2017

How to print to STDERR in Clojure came up the other day.

It turns out there are two vars *out* and *err* that are bound to STDOUT and STDERR. There vars are instances of `java.io.PrintWriter' and you can simply write to them.

For example, here is a string being printed to STDOUT.

user> (.println *out* "hello")
hello
nil

The same can be done for STDERR. Just send a string out through *err*.

 (.println *out* "hello")
hello
nil

In addition you can also send something to *err* by temporarily binding the value of *out* to the current value of *err*. This allows you use your normal println function and have it's output go to a different place.

  (binding [*out* *err*]
    (println msg))

The repo linked below has a simple Clojure project you can build and run to show both techniques.


Tags: clojure