Executing a shell command from Common Lisp

2020-02-08 06:05发布

How can i execute a shell (bash) command within a Common Lisp program and assign the output to a variable?

8条回答
趁早两清
2楼-- · 2020-02-08 06:24

You can consider using Trivial-shell (url)

(trivial-shell:shell-command "echo foo")

shell-command returns output, so you can assign it to a variable.

In asdf.lisp file you can read:

;;;; We probably should move this functionality to its own system and deprecate

;;;; use of it from the asdf package. However, this would break unspecified

;;;; existing software, so until a clear alternative exists, we can't deprecate

;;;; it, and even after it's been deprecated, we will support it for a few

;;;; years so everyone has time to migrate away from it. -- fare 2009-12-01

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-08 06:27

ASDF provides a RUN-SHELL-COMMAND that works with many Common Lisp implementations including ABCL, Allegro CL, CLISP, Clozure CL, ECL, GCL, LispWorks, SBCL, CMU, XCL and SCL.

It takes a control string and a list of arguments like FORMAT, and synchronously executes the result using a Bourne-compatible shell. Capture output by binding an optional stream.

查看更多
做个烂人
4楼-- · 2020-02-08 06:27

I tried out some answers but it was not straightforward. This is what worked easily:

(ql:quickload "external-program")
;; run shell command e.g. "ls -l" and capture the output into string *output*
(defparameter *output* 
              (with-output-to-string (out) 
                (external-program:run "ls" '("-l")  ; command with parameters as list of strings
                                      :output out)))
;; and after that, you can write functions to parse the output ...

This is from Edi Weitz's book Common Lisp Recipes which belongs to the shelve of any serious Lisp programmer, in my view...

查看更多
小情绪 Triste *
5楼-- · 2020-02-08 06:31

In sbcl:

(sb-ext:run-program "/bin/sh" (list "-c" "whoami") :input nil :output *standard-output*)

It works fine for me:)

查看更多
成全新的幸福
6楼-- · 2020-02-08 06:32

Some CL implementations have built-in functions for this purpose. For example, SBCL has sb-ext:run-program, and CCL has run-program.

查看更多
时光不老,我们不散
7楼-- · 2020-02-08 06:33

Nowadays I would use uiop:run-program, where uiop stands for "universal input output" and is a compatibility layer provided by asdf3, formerly known as asdf/driver. As has been said asdf:run-shell-command is obsolete and uiop inherits many features of other libraries such as trivial-shell.

UIOP readme

查看更多
登录 后发表回答