Wanting stdout, stderr and return code of shell commands

Started by Ishpeck, November 08, 2011, 01:37:44 PM

Previous topic - Next topic

Ishpeck

When I use exec or ! to run a shell command, I want to get strings containing the contents of stdout and stderr (even if empty) as well as the exit code of the program.



I could direct the output in the command like so:

(! "ls 2>/tmp/err >/tmp/out")



And then just read those files but that seems horribly crufty.

 

Now exec gives me stdout but I still  want exit code and stderr.



Is there a better way to see what is happening with the programs I run?

jef

Old post but it's worth a reply as I was also looking for a solution.

process and waitpid can be used. An example returning stdout/stderr

combined and the return code of the command:



(define (exec2 cmd)
  (let ((pid) (out_r) (out_w) (output) (data))
    (map set '(out_r out_w) (pipe))
    (setq pid (process cmd 0 out_w))
    (close out_w)
    (while (read out_r data 1024)
           (extend output data))
    (list output (>> ((wait-pid pid) 1) 8))))


Examples of the execution of a successful and a failed command:

 

> (exec2 "/bin/echo pouet")
("pouetn" 0)

> (exec2 "/bin/ls /root")
("/bin/ls: cannot open directory /root: Permission deniedn" 2)

rrq

It depends on the platform of course. With bash and similar, you could also have
(define (exec2 cmd) (exec (string cmd " 2>&1 ; echo $?"))
That will nicely parse and deliver the output (stdout and stderr) as a list of lines, with the addition of the return code as an additional string element at the end.