简体   繁体   中英

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

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?

You can use with-output-to-string for this. 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 .

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* . (The fact that format instead takes nil to mean that it should return a string is a common point of confusion).

Keep in mind that portably errors are made with MAKE-CONDITION . The standard does not say that errors are CLOS classes, so MAKE-INSTANCE might not work in some implementations.

There are two simple ways to get a string:

a) a textual description:

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

b) the error object printed:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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