如何在EMACS中使用Elisp将标准输出重定向到文件

3

我使用with-output-to-temp-buffer函数,将标准输出重定向到它,然后将其保存到文件中,切换回之前的缓冲区,最后删除临时缓冲区。

(require 'find-lisp)
(with-output-to-temp-buffer "*my output*" 
  (mapc 'print (find-lisp-find-files "~/project/clisp" "\\.lisp$"))
  (setq prev-buffer (buffer-name))
  (switch-to-buffer "*my output*")
  (write-region nil nil "test")
  (switch-to-buffer prev-buffer)
  (kill-buffer "*my output*")
  )

但是下面的错误发生了。我不知道为什么。
Debugger entered--Lisp error: (error "Selecting deleted buffer")

PS:有没有更优雅的方式在Elsip中实现这个操作(将标准输出重定向到文件)。谢谢。

1个回答

9
这个错误是由于 with-output-to-temp-buffer 尝试在计算完其主体后显示缓冲区,但此时您已经删除了该缓冲区。我认为您需要使用的宏是 with-temp-file。它的文档字符串如下:

(with-temp-file FILE &rest BODY)

创建一个新的缓冲区,在其中计算BODY并将缓冲区写入FILE。

然后,您可以将 standard-output 绑定到新的缓冲区,例如:
(with-temp-file "test.txt"
  (let ((standard-output (current-buffer)))
    (mapc 'print (find-lisp-find-files "~/project/clisp" "\\.lisp$"))))

1
楼修:有关该错误的进一步说明,请参见“C-h f with-output-to-temp-buffer RET”。 - phils

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接