【问题标题】:running shell commands with gnu clisp使用 gnu clisp 运行 shell 命令
【发布时间】:2010-06-10 22:59:04
【问题描述】:

我正在尝试为 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

【问题讨论】:

    标签: lisp stream clisp


    【解决方案1】:

    这样的?

    版本 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
    ..."
    

    【讨论】:

    • 问题: :output 表示什么?这是命名参数语法吗?
    • :output 是一个参数,用于设置输出将定向到的位置。在此它将被定向到一个流。
    【解决方案2】:

    根据CLISP documentation on run-program:output 参数应该是其中之一

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

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

    【讨论】:

      【解决方案3】:

      您是在专门询问 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 文档中搜索运行程序:http://ccl.clozure.com/ccl-documentation.html

      在这个 * 答案中有几个很好的 Lisp 方法可以做到这一点:Making a system call that returns the stdout output as a string 再一次,Rainer 来救援。谢谢拉尼尔。

      【讨论】:

        【解决方案4】:

        这个比较短

        (defun system(cmd)
          (ext:shell (string cmd)))
        
        > (system '"cd ..; ls -lrt; pwd")
        

        【讨论】:

          最近更新 更多