当我在lisp中执行特定功能时,我想保存或忽略输出。我使用Emacs和CCL。例如,
(defun foo (x) (format t "x = ~s~%" x))
如果我执行该函数,则打印出“x = 5”。但我不想在缓冲区中打印输出,因为如果我有大量的迭代,模拟的速度将会降低。
有什么想法吗?
答案 0 :(得分:8)
您可以通过将*standard-output*
绑定到流来临时重定向标准输出。例如,没有输出流的broadcast stream将作为输出的黑洞:
(let ((*standard-output* (make-broadcast-stream)))
(foo 10)
(foo 20))
;; Does not output anything.
您也可以使用其他绑定结构执行此操作,例如with-output-to-string
或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.
答案 1 :(得分:2)
而不是t
作为format
的第一个参数,您可以为其提供输出文件流,并将该语句的输出发送到该文件流。
但是,过多的磁盘I / O也会增加您的运行时间,因此您可以考虑为您的程序设置两种模式,如调试和发布模式,其中调试模式打印所有诊断消息,而释放模式不打印任何东西。
答案 2 :(得分:1)
我不确定我理解你的问题,但format
的第二个论点是stream。如果将其设置为t
,则会将其打印到标准输出,但您也可以将其设置为打开文件。
所以这样的事情可以让你选择输出的位置:
;;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