Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print to STDERR in Clojure?

Tags:

clojure

The println function writes to STDOUT. How can we write messages to STDERR instead?

(println "Hello, STDOUT!") 
like image 709
Drew Noakes Avatar asked Feb 25 '14 16:02

Drew Noakes


2 Answers

There is no specific function for this, however you can dynamically rebind the var holding the stream that println writes to like this:

(println "Hello, STDOUT!")  (binding [*out* *err*]   (println "Hello, STDERR!")) 

In my REPL, the colour indicates the stream (red is STDERR):

enter image description here

like image 178
Drew Noakes Avatar answered Sep 17 '22 13:09

Drew Noakes


Plain Java methods work fine and will be understood easily by Clojure novices:

(.println *err* "Hello, STDERR!") 

Another alternative, just for fun, is clojure.java.io/copy:

(require '[clojure.java.io :as cjio])  (cjio/copy "Hello, STDERR!\n" *err*) (.flush *err*) 
like image 44
matvore Avatar answered Sep 19 '22 13:09

matvore