在 Common Lisp 中获取命令行参数
-
06-07-2019 - |
题
如何获取 Common Lisp 中的命令行参数(特别是在 GNU 中,如果有任何差异)?
解决方案
我假设您使用CLisp编写脚本。您可以创建包含
的文件#! /usr/local/bin/clisp
(format t "~&~S~&" *args*)
通过运行
使其可执行$ chmod 755 <filename>
运行它给出了
$ ./<filename>
NIL
$ ./<filename> a b c
("a" "b" "c")
$ ./<filename> "a b c" 1 2 3
("a b c" "1" "2" "3")
其他提示
http://cl-cookbook.sourceforge.net/os.html 提供了一些见解
(defun my-command-line ()
(or
#+CLISP *args*
#+SBCL *posix-argv*
#+LISPWORKS system:*line-arguments-list*
#+CMU extensions:*command-line-words*
nil))
我想这就是你正在寻找的。
您在谈论Clisp还是GCL?似乎在GCL中,命令行参数在 si :: * command-args *
中传递。
在SBCL中,我们可以使用sb-ext:* posix-argv *从常见的lisp脚本中获取argv。 sb-ext:* posix-argv *是一个包含所有参数的列表,第一个arg是脚本filname。
有一个提到的Clon库为每个实现提取机制,现在也更简单的 unix-opts 和关于食谱的教程
(ql:quickload "unix-opts")
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help")
(:name :nb
:description "here we want a number argument"
:short #\n
:long "nb"
:arg-parser #'parse-integer) ;; <- takes an argument
(:name :info
:description "info"
:short #\i
:long "info"))
然后使用(opts:get-opts)
完成实际的解析,它返回两个值:选项和剩余的自由参数。
如 https://stackoverflow.com/a/1021843/31615 所示,每个实施都有自己的机制。处理此问题的常用方法是使用包装器库,为您提供统一的界面。
这样的库不仅可以提供进一步的帮助,还可以转换它们并为用户提供有用的输出。一个非常完整的包是CLON(不要与CLON或CLON混淆,抱歉),命令行选项Nuker ,它还带来了大量文档。但是,如果您的需求更轻松,还有其他一些,例如,命令行参数和 apply-argv 。
quicklisp中的软件包分别命名为 net.didierverna.clon
, command-line-arguments
和 apply-argv
不隶属于 StackOverflow