我使用shell-command-to-string
从shell调用命令。但是,我不仅需要它的输出,还需要命令的退出代码。
我如何得到这个?
答案 0 :(得分:14)
shell-command-to-string
只是围绕更基本过程函数的便利包装。
用于简单同步过程的一个好函数是call-process
。调用进程将返回进程的退出代码,您可以将所有输出重定向到可以使用buffer-string
打开的缓冲区来获取文本。
以下是一个例子:
;; this single expression returns a list of two elements, the process
;; exit code, and the process output
(with-temp-buffer
(list (call-process "ls" nil (current-buffer) nil "-h" "-l")
(buffer-string)))
;; we could wrap it up nicely:
(defun process-exit-code-and-output (program &rest args)
"Run PROGRAM with ARGS and return the exit code and output in a list."
(with-temp-buffer
(list (apply 'call-process program nil (current-buffer) nil args)
(buffer-string))))
(process-exit-code-and-output "ls" "-h" "-l" "-a") ;; => (0 "-r-w-r-- 1 ...")
另一个注意事项:如果你最终想要对流程做更复杂的事情,你应该阅读start-process
的文档,以及如何使用sentinals和过滤器,它真的是一个强大的api。