在elisp中查找shell命令的退出代码

Cla*_*bel 9 emacs elisp

我使用shell调用shell命令shell-command-to-string.但是,我不仅需要它的输出,还需要命令的退出代码.

我怎么得到这个?

Jor*_*ndo 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 ...")
Run Code Online (Sandbox Code Playgroud)

另一个注意事项:如果你最终想要对进程做更复杂的事情,你应该阅读文档start-process,以及如何使用sentinals和过滤器,它真的是一个强大的API.

  • 传递给“call-process”的参数是可变的,这意味着我不能将参数从“process-exit-code-and-output”传递到“call-process”,因为它需要许多参数,而不是列表参数。“apply”是一个简洁的函数,因为它也使用可变参数,但它是一种特殊的行为。如果“apply”的最后一个参数是一个列表,则使用这些元素就好像它们是单独给出的一样。这样做是为了在使用可变参数的情况下方便。例如: (apply '+ 1 2 3 (4 5)) == (apply '+ 1 2 3 4 5) (2认同)