質問

I call a command from the shell using shell-command-to-string. However, I want not only its output, but also the command's exit code.

How do I get this?

役に立ちましたか?

解決

shell-command-to-string is just a convenience wrapper around more fundamental process functions.

A good function to use for simple synchronous processes is call-process. Call process will return the exit code from the process and you can redirect all output to a buffer that you can use buffer-string on to get the text.

Here's an example:

;; 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 ...")

Another note: if you end up wanting to do anything more complex with processes, you should read the documentation for start-process, and how to use sentinals and filters, it is really a powerful api.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top