Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to capture prints to *out* from a Clojure function?

Tags:

stdout

clojure

For example, the prxml function prints XML to *out*. I would like to instead capture this output as a String. Here is the typical usage from a REPL:

user> (prxml [:p "Test"])
<p>Test</p>nil

I'd instead like to do:

(def xml (capture-out (prxml [:p "Test"])))

I made up the capture-out function, but I suspect something like it exists, only I'm having trouble finding it in the API or mailing list.

like image 297
Robert Campbell Avatar asked Dec 03 '09 12:12

Robert Campbell


2 Answers

I just discovered the with-out-str from this great blog post detailing XML processing in Clojure.

So the correct implementation of my example is:

(def xml (with-out-str (prxml [:p "Test"])))
like image 191
Robert Campbell Avatar answered Sep 28 '22 22:09

Robert Campbell


More generally, if you look at the source for with-out-str you can see how to dynamically bind *out* to any stream using binding. This works for dynamically setting the value of any existing var.

like image 41
Hugo Duncan Avatar answered Sep 28 '22 22:09

Hugo Duncan