guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Shell commands with output to string


From: Leo Butler
Subject: Re: Shell commands with output to string
Date: Tue, 22 Feb 2022 10:00:00 -0600
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.1 (gnu/linux)

Olivier Dion via General Guile related discussions <guile-user@gnu.org>
writes:

> On Tue, 22 Feb 2022, Zelphir Kaltstahl <zelphirkaltstahl@posteo.de> wrote:
>> Hello Guile users!
>>
>> How would I run a shell command from inside Guile and get its output
>> as a string, instead of the output being outputted directly? (Guile
>> 3.0.8)
>
> I use the following:
>
> (define-module (shell utils)
>   #:use-module (ice-9 format)
>   #:use-module (ice-9 popen)
>   #:use-module (ice-9 textual-ports))
>
> (define (shell% proc fmt . args)
>   (let* ((port (open-input-pipe (format #f "~?" fmt args)))
>          (output (proc port)))
>     (close-pipe port)
>     output))

You probably want to inspect the exit value of the shell process, so
that you can handle/throw the error. This is what I use (similar to your
`shell'):

(define* (shell-command-to-string cmd)
  (catch 'shell-command-error
    ;; thunk                                                                    
                                                                                
                                                                    
    (lambda ()
      (let* ((port (open-pipe cmd OPEN_READ))
             (str (read-string port))
             (wtpd (close-pipe port))
             (xval (status:exit-val wtpd)))
        (if (or (eqv? xval #f) (> xval 0)) (throw 'shell-command-error cmd str))
        str))
    ;; handler                                                                  
                                                                                
                                                                    
    (lambda (key cmd str)
      (simple-format #t "ERROR: in command ~a\nstring: ~a\n" cmd str)
      (throw 'error-in-shell-command-to-string cmd str))))

>
> (define-public (shell . args)
>   (apply shell% (cons get-string-all args)))
>
> (define-public (shell$ . args)
>   (apply shell% (cons get-line args)))
>
> Then
> (shell "ls" "-l")
>
> The $ variant is to get a single line in the output.

I wonder why there is no module already in ice-9 which does this stuff?
It seems like a lot of people are re-inventing the wheel.

Leo



reply via email to

[Prev in Thread] Current Thread [Next in Thread]