I have a function which returns a value and prints data to stdout and stderr. I cannot modify this function. I would now like to execute this function, capturing the data printed to stdout and stderr, storing it in two separate variables. If possible, I'd also like to store the function's return value in a third variable.
I've come accross (with-output-to-string (*standard-output*) ...)
but this won't let me capture both stdout and stderr. What options do I have?
You could just use let
to bind the streams to output string streams. For example:
(defun print-stuff (x y)
(format t "standard output ~a" x)
(format *error-output* "error output ~a" y)
(+ x y))
(defun capture (x y)
(let ((*standard-output* (make-string-output-stream))
(*error-output* (make-string-output-stream)))
(values (print-stuff x y)
(get-output-stream-string *standard-output*)
(get-output-stream-string *error-output*))))
(capture 43 12)
; => 55
; "standard output 43"
; "error output 12"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With