简体   繁体   English

如何在没有实际打印的情况下从(错误)对象生成字符串?

[英]How to generate a string out of an (error)object without actual printing?

I want to retrieve the string, generated by write for further processing without doing any actual output, but write seems always to also output into the REPL 我想检索由write生成的字符串,以便在不进行任何实际输出的情况下进行进一步处理,但是write似乎总是也输出到REPL中

CL-USER>(let ((err-string (write (make-instance 'error) :stream nil)))
          (do-awesome-stuff-with-string err-string))
<ERROR> ;;this is the printing I want to get rid of
"awesome-result"

Why does write still outputs into the REPL, and how do I get rid of that? 为什么write还是输出到REPL,以及我如何摆脱呢?

You can use with-output-to-string for this. 您可以为此使用with-output-to-string Here's an example: 这是一个例子:

(flet ((do-awesome-stuff-with-string (string)
         (concatenate 'string string " is awesome!")))
  (let ((err-string (with-output-to-string (s)
                      (write (make-instance 'error) :stream s))))
    (do-awesome-stuff-with-string err-string)))
;; => "#<ERROR {25813951}> is awesome!"

Here's here's the HyperSpec entry on with-output-to-string . 这里的下面是对HyperSpec进入with-output-to-string

The reason (write (make-instance 'error) :stream nil) doesn't work is that the :stream argument to write is a stream designator and in that context nil is shorthand for *standard-output* . 原因(write (make-instance 'error) :stream nil)不起作用是因为write:stream参数是一个流指示符 ,在这种情况下nil*standard-output*简写。 (The fact that format instead takes nil to mean that it should return a string is a common point of confusion). format实际上取nil表示它应该返回一个字符串,这是一个常见的混淆点)。

Keep in mind that portably errors are made with MAKE-CONDITION . 请记住, MAKE-CONDITION产生可移植的错误。 The standard does not say that errors are CLOS classes, so MAKE-INSTANCE might not work in some implementations. 该标准没有说错误是CLOS类,因此MAKE-INSTANCE在某些实现中可能不起作用。

There are two simple ways to get a string: 有两种简单的方法来获取字符串:

a) a textual description: a)文字说明:

CL-USER 15 > (princ-to-string (make-condition 'error))
"The condition #<ERROR 4020311270> occurred"

b) the error object printed: b)打印的错误对象:

CL-USER 16 > (prin1-to-string (make-condition 'error))
"#<ERROR 402031158B>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM