user1024748
user1024748

Reputation: 41

Print output into a file or not print output?

I'd like to save or ignore outputs when I execute a specific function in lisp. I use Emacs and CCL. For example,

(defun foo (x) (format t "x = ~s~%" x))

and if I execute the function, it prints out "x = 5". But I don't want to printout in a buffer, because if I have a large amount of iteration, the speed of simulation will be decreased.

Any idea?

Upvotes: 4

Views: 1490

Answers (3)

Matthias Benkard
Matthias Benkard

Reputation: 15759

You can temporarily redirect standard output by binding *standard-output* to a stream. For example, a broadcast stream with no output streams will serve as a black hole for output:

(let ((*standard-output* (make-broadcast-stream)))
  (foo 10)
  (foo 20))
;; Does not output anything.

You can also do this with other binding constructs, such as with-output-to-string or with-open-file:

(with-output-to-string (*standard-output*)
  (foo 10)
  (foo 20))
;; Does not print anything;
;; returns the output as a string instead.

(with-open-file (*standard-output* "/tmp/foo.txt" :direction :output)
  (foo 10)
  (foo 20))
;; Does not print anything;
;; writes the output to /tmp/foo.txt instead.

Upvotes: 8

loudandclear
loudandclear

Reputation: 2386

Instead of t as the first argument to format, you can give it an output file stream and your output for that statement will be sent to that file stream.

However having excessive disk I/O will also will increase your running time, hence you can consider having two modes like a debug and a release mode for your program where the debug mode prints all the diagnostic messages and the release mode does not print anything at all.

Upvotes: 2

Tyler
Tyler

Reputation: 10032

I'm not sure I understand your question, but the second argument to format is a stream. If you set it to t it prints to standard output, but you can also set it to an open file.

So something like this would allow you to select where the output goes:

;;output to file:
(setf *stream* (open "myfile" :direction :output
                              :if-exists :supersede)

;;alternative to output to standard output:
;;(setf *stream* t)

(defun foo (x) (format *stream* "x = ~s~%" x))

(foo 10)
(close *stream*) ;; only if output sent to a file

Upvotes: 1

Related Questions