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.

Drew
  • 75,699
  • 9
  • 109
  • 225
ideasman42
  • 8,375
  • 1
  • 28
  • 105

1 Answers1

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
"
xuchunyang
  • 14,302
  • 1
  • 18
  • 39
  • Can't this be done without using the buffer as an intermediate step? – ideasman42 Apr 07 '20 at 08: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 07 '20 at 08: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 07 '20 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 08 '20 at 00: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 08 '20 at 00:18