我有一个函数,它返回一个值并将数据打印到stdout和stderr。我无法修改此功能。我现在想要执行此函数,捕获打印到stdout和stderr的数据,将其存储在两个单独的变量中。如果可能的话,我还想将函数的返回值存储在第三个变量中。
我来到了(with-output-to-string (*standard-output*) ...)
,但这不会让我捕获stdout和stderr。我有什么选择?
答案 0 :(得分:9)
您可以使用let
将流绑定到输出字符串流。例如:
(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"