将输出打印到文件中或不打印输出?
我想在lisp中执行特定函数时保存或忽略输出。我使用Emacs和CCL。例如,将输出打印到文件中或不打印输出?
(defun foo (x) (format t "x = ~s~%" x))
,如果我执行的功能,它打印出 “X = 5”。但是我不想在缓冲区中打印输出,因为如果我有大量的迭代,模拟的速度将会降低。
有什么想法?
我不知道我理解你的问题,但第二个参数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
代替t
作为第一个参数format
,你可以给它一个输出文件流和你的说法输出会被发送到该文件流。
但是有过多的磁盘I/O也将增加运行时间,因此你可以考虑有两个模式,如调试,并为你的程序的释放模式,其中调试模式下打印出所有的诊断消息和释放模式不根本不打印任何东西。
感谢您的意见。但是我真正想要的是,就像一个C程序一样,你可以运行一个像foo> a.txt这样的程序,如果这样的话,输出结果就会打印在一个.txt文件中。我想知道是否有任何方法可以在lisp中做到这一点。 – user1024748
编译代码后,您仍然可以使用'a.txt'重定向可执行文件的标准输出。 另一种方法是调用像'CLISP> a.txt'解释。这样所有的REPL和你的标准输出将被重定向到'a.txt' – loudandclear
响亮而清晰,我不太理解你的评论。你能详细解释一下吗? – user1024748
可以暂时通过结合*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.
的问题是不清楚,'(格式t ...)'看起来不正确,是elisp还是Clojure还是......? – 2011-11-02 01:00:02
(format t ...)是Common Lisp,不是elisp。我认为这与Emacs没有任何关系。 – Tyler