【问题标题】:lisp: capture stdout and stderr, store it in separate variableslisp:捕获标准输出和标准错误,将其存储在单独的变量中
【发布时间】:2016-02-11 07:58:31
【问题描述】:

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

我遇到了(with-output-to-string (*standard-output*) ...),但这不会让我同时捕获标准输出和标准错误。我有什么选择?

【问题讨论】:

  • 嵌套两个怎么样,每个字符串一个?
  • 这确实有效,但对我来说似乎有些不雅。还有其他方法可以实现吗?

标签: lisp common-lisp sbcl


【解决方案1】:

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

【讨论】:

  • 这正是我想要的。谢谢!
  • 有时会使用*trace-output*,比如(时间形式)函数。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 2013-05-11
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
相关资源
最近更新 更多