如何使用sbcl来使用shell命令

How to use sbcl to use shell command

我想编写一个直接打开文件的功能。喜欢python代码:

os.system("ls")

比如我使用这个功能(fun_open "/path/to/file"),系统会使用默认的app打开文件。如果文件是 .txt,用 textedit 打开它。

如何制作?

----2015 年 9 月 24 日更新-----

我的代码是:

(defun open_by_system (dir)
  (sb-ext:run-program "/usr/bin/open" (list "-a" "Preview" dir)))

我用它:

CL-USER> (open_by_system "~/Desktop/ML.pdf")
#<SB-IMPL::PROCESS :EXITED 1>

没有其他事情发生

Mac OS X 和 SBCL:

在默认文本编辑器应用程序 TextEdit 中打开一个文本文件:

Lisp Machine:~ lispm$ touch /tmp/test.text

Lisp Machine:~ lispm$ sbcl
This is SBCL 1.2.14, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.

* (sb-ext:run-program "/usr/bin/open" '("/tmp/test.text"))

#<SB-IMPL::PROCESS :EXITED 0>

使用 LispWorks 作为文本编辑器打开文件:

* (sb-ext:run-program
    "/usr/bin/open"
    '("-a"
      "/Applications/LispWorks 7.0 (64-bit)/LispWorks (64-bit).app"
      "/tmp/test.text"))

对于此类问题,您可能需要查阅 SBCL 手册。例如关于 Running External Programs.

的章节

我建议使用 UIOP,它为 OS 提供了可移植的接口,并且作为 ASDF3 的一部分普遍可用:

(uiop:run-program "ls")

有关详细信息,请参阅 run-program.lisp 中的文档字符串。

如果您需要更多便利功能,可以查看inferior-shell

我建议您查看 quickdocs 上可用的库:

link

我建议你使用 quicklisp

上可用的 inferior-shell

link

正在加载:

CL-USER> (ql:quickload 'inferior-shell)
To load "inferior-shell":
  Load 5 ASDF systems:
    alexandria asdf closer-mop named-readtables optima
  Install 4 Quicklisp releases:
    fare-mop fare-quasiquote fare-utils inferior-shell
; Fetching #<URL "http://beta.quicklisp.org/archive/fare-quasiquote/2015-06-08/fare-quasiquote-20150608-git.tgz">
; 15.08KB
==================================================
15,437 bytes in 0.10 seconds (157.03KB/sec)
; Fetching #<URL "http://beta.quicklisp.org/archive/fare-utils/2015-06-08/fare-utils-20150608-git.tgz">
; 31.51KB
==================================================
32,264 bytes in 0.14 seconds (218.80KB/sec)
; Fetching #<URL "http://beta.quicklisp.org/archive/fare-mop/2015-06-08/fare-mop-20150608-git.tgz">
; 2.67KB
==================================================
2,738 bytes in 0.00 seconds (0.00KB/sec)
; Fetching #<URL "http://beta.quicklisp.org/archive/inferior-shell/2015-06-08/inferior-shell-20150608-git.tgz">
; 12.87KB
==================================================
13,182 bytes in 0.00 seconds (12873.05KB/sec)
; Loading "inferior-shell"
[package fare-utils]..............................
[package fare-stateful]...........................
[package fare-quasiquote].........................
[package fare-mop].............
(INFERIOR-SHELL)

一个简单的示例:

CL-USER> (inferior-shell:run/ss '(echo (1) "2" (+ 3)))
"1 2 3"
NIL
0

带管道的示例:

CL-USER> (inferior-shell:run/ss `(inferior-shell:pipe (echo (+ hel "lo,") world) (tr "hw" "HW") (sed -e "s/$/!/")))
"Hello, World!"
NIL
0