Lisp: capture stdout and stderr, save in separate variables

I have a function that returns a value and prints data to stdout and stderr. I can not change this function. Now I would like to execute this function by taking the data printed on stdout and stderr and storing them in two separate variables. If possible, I would also like to store the return value of the function in a third variable.

I came on (with-output-to-string (*standard-output*) ...), but that will not allow me to capture both stdout and stderr. What are my options?

+4
source share
1 answer

You can simply use letto bind 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"
+9

Source: https://habr.com/ru/post/1628263/


All Articles