Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lisp: capture stdout and stderr, store it in separate variables

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?

like image 303
watain Avatar asked Dec 19 '22 19:12

watain


1 Answers

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"
like image 121
jkiiski Avatar answered Feb 19 '23 02:02

jkiiski