如何在elisp中捕获shell命令的标准输出?

51

我希望在Emacs中运行一个shell命令并将完整输出捕获到一个变量中。是否有办法做到这一点?例如,我想以以下方式设置hello-string变量为"hello"

(setq hello-string (capture-stdout-of-shell-command "/bin/echo hello"))

函数capture-stdout-of-shell-command是否存在,如果存在,它的真实名称是什么?

2个回答

81

7
请注意,“shell-command-to-string”命令会捕获“stdout”和“stderr”。幸运的是,我们可以将stderr重定向到/dev/null:((shell-command-to-string "/bin/echo hello 2>/dev/null"))。 - Yorick Sijsling

27

我有一个建议可以扩展Ise Wisteria的答案。尝试使用类似这样的代码:

(setq my_shell_output
  (substring 
    (shell-command-to-string "/bin/echo hello") 
   0 -1))

这应该将字符串"hello"设置为my_shell_output的值,但是要干净利落。使用(substring)可以消除当emacs调用shell命令时会出现的尾随\n。它在Windows上运行的emacs中使我感到困扰,并且可能也会在其他平台上发生。


2
我注意到 Emacs 在 Mac OS X 和 Linux 上都会这样做,所以这不仅仅是 NTEmacs 才有的现象。 - Brighid McDonnell
2
(defun my-shell-command-to-string (&rest cmd) (replace-regexp-in-string "\r?\n$" "" (shell-command-to-string (mapconcat 'identity cmd " ")))) - spacebat
2
@spacebat 你需要放入 \\',而不是 $ - Clément
1
“echo hello” 是 “hello\n”。 - d12frosted
4
在Linux/OSX中,可以使用-n来停止输出结尾的换行符。例如,echo -n hello - Chuan Ma
1
根据Yorick的评论,与(shell-command-to-string "/bin/echo hello 2>/dev/null")组合使用时无法正常工作。有没有处理可能为空字符串的提示? - Marcin

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