Making a system call that returns the stdout output as a string

前端 未结 27 1262
误落风尘
误落风尘 2020-11-27 05:13

Perl and PHP do this with backticks. For example,

$output = `ls`;

Returns a directory listing. A similar function, system(\"foo\")

27条回答
  •  天命终不由人
    2020-11-27 05:50

    Here's another Lisp way:

    (defun execute (program parameters &optional (buffer-size 1000))
      (let ((proc (sb-ext:run-program program parameters :search t :output :stream))
            (output (make-array buffer-size :adjustable t :fill-pointer t 
                                :element-type 'character)))
        (with-open-stream (stream (sb-ext:process-output proc))
          (setf (fill-pointer output) (read-sequence output stream)))
        output))
    

    Then, to get your string:

    (execute "cat" '("/etc/hosts"))
    

    If you want to run a command that creates prints a great deal of info to STDOUT, you can run it like this:

    (execute "big-writer" '("some" "parameters") 1000000)
    

    The last parameter preallocates a large amount of space for the output from big-writer. I'm guessing this function could be faster than reading the output stream one line at a time.

提交回复
热议问题