2

Currently I'm generating text from a command, eg:

(with-temp-buffer
  (call-process "my-command" nil t nil "my" "args")
  ;; operate on output in current buffer.
  )

How can I use pipes, something that would be written in shell like this:

my-command my args | wc -l


Note, this is just an example command, doing the same operation without pipes wont address this question.

1 Answer 1

2

Use the system shell, e.g., M-! ls | wc, there are many other APIs such as shell-command-to-string, call-process-shell-command and start-process-shell-command.

An idea is emulating pipe like the following, it is slow since the second process won't run until the first is done. Though it's possible to use asynchronous process + process filter to avoiding blocking, it's still going to be slow. (Take Eshell for example)

(with-temp-buffer
  (call-process "date" nil t)
  (call-process-region nil nil "wc" nil t t )
  (buffer-string))
;; =>
"Tue Apr  7 15:49:17 CST 2020
       1       6      29
"
5
  • Can't this be done without using the buffer as an intermediate step?
    – ideasman42
    Apr 7, 2020 at 8:19
  • 1
    @ideasman42 It seems possible using asynchronous process, you get output from process with process-filter, and send input to process with process-send-string, both of them uses string.
    – xuchunyang
    Apr 7, 2020 at 8:56
  • A third option is to create temporary files and pass them as the second and third arguments to call-process. Apart from potentially being faster than using an Emacs buffer, though, I don't see any other benefits to this approach.
    – Basil
    Apr 7, 2020 at 15:40
  • @Basil that's only an option if the process accepts the input as an argument, which isn't always the case.
    – ideasman42
    Apr 8, 2020 at 0:09
  • 1
    @ideasman42 Specifying a file as the stdout of one process and the stdin of another, which the second and third arguments to call-process allow, has nothing to do with what arguments the process accepts.
    – Basil
    Apr 8, 2020 at 0:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.