我有一个函数,它返回一个值并将数据打印到标准输出和标准错误。我无法修改此功能。我现在想执行此函数,捕获打印到 stdout 和 stderr 的数据,并将其存储在两个单独的变量中。如果可能,我还想将函数的返回值存储在第三个变量中。
我遇到了 (with-output-to-string (*standard-output*) ...)
但这不会让我同时捕获 stdout 和 stderr。我有哪些选择?
最佳答案
您可以只使用 let
将流绑定(bind)到输出字符串流。例如:
(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"
关于lisp:捕获标准输出和标准错误,将其存储在单独的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35333715/