lisp:捕获标准输出和标准错误,将其存储在单独的变量中

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

我有一个函数,它 return 是一个值并将数据打印到 stdout 和 stderr。我无法修改此功能。我现在想执行此函数,捕获打印到 stdout 和 stderr 的数据,并将其存储在两个单独的变量中。如果可能的话,我还想将函数的 return 值存储在第三个变量中。

我遇到了 (with-output-to-string (*standard-output*) ...) 但这不会让我同时捕获 stdout 和 stderr。我有哪些选择?

您可以只使用 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"