使用gnu clisp运行shell命令

时间:2010-06-10 22:59:05

标签: lisp stream clisp

我正在尝试为clisp创建一个像这样工作的“系统”命令

(setq result (system "pwd"))

;;now result is equal to /my/path/here

我有这样的事情:

(defun system (cmd)
 (ext:run-program :output :stream))

但是,我不确定如何将流转换为字符串。我已经多次回顾了hyperspec和google。

编辑:使用Ranier的命令并使用with-output-to-stream,

(defun system (cmd)
  (with-output-to-string (stream)
    (ext:run-program cmd :output stream)))

然后尝试运行grep,这是我的路径......

[11]> (system "grep")

*** - STRING: argument #<OUTPUT STRING-OUTPUT-STREAM> should be a string, a
      symbol or a character
The following restarts are available:
USE-VALUE      :R1      Input a value to be used instead.
ABORT          :R2      Abort main loop
Break 1 [12]> :r2

4 个答案:

答案 0 :(得分:5)

这样的东西?

第2版:

(defun copy-stream (in out)
   (loop for line = (read-line in nil nil)
         while line
         do (write-line line out)))

(defun system (cmd)
  (with-open-stream (s1 (ext:run-program cmd :output :stream))
    (with-output-to-string (out)
      (copy-stream s1 out))))


[6]> (system "ls")
"#.emacs#
Applications
..."

答案 1 :(得分:3)

根据CLISP documentation on run-program:output参数应为

之一
  • :terminal - 写入终端
  • :stream - 创建并返回输入流,您可以从中读取
  • 路径名指示符 - 写入指定文件
  • nil - 忽略输出

如果您希望将输出收集到字符串中,则必须使用读写复制循环将数据从返回的流传输到字符串。根据Rainer的建议,你已经有了with-output-to-string,但是你不需要将输出流提供给run-program,而是需要自己写入,从输入流中复制数据< / em>由run-program返回。

答案 2 :(得分:2)

你是专门询问clisp的。我在这里补充一下 如果你使用Clozure CL,那么你也可以轻松运行os子进程。

一些例子:

;;; Capture the output of the "uname" program in a lisp string-stream
;;; and return the generated string (which will contain a trailing
;;; newline.)
? (with-output-to-string (stream)
    (run-program "uname" '("-r") :output stream))
;;; Write a string to *STANDARD-OUTPUT*, the hard way.
? (run-program "cat" () :input (make-string-input-stream "hello") :output t)
;;; Find out that "ls" doesn't expand wildcards.
? (run-program "ls" '("*.lisp") :output t)
;;; Let the shell expand wildcards.
? (run-program "sh" '("-c" "ls *.lisp") :output t)

在位于此处的CCL文档中搜索run-program:http://ccl.clozure.com/ccl-documentation.html

在这个stackoverflow答案中,有一些很好的Lisp方法可以做到这一点:Making a system call that returns the stdout output as a string再一次,Rainer拯救了。谢谢Ranier。

答案 3 :(得分:0)

这是一个较短的

(defun system(cmd)
  (ext:shell (string cmd)))

> (system '"cd ..; ls -lrt; pwd")