我想在Common Lisp中获取和解析命令行参数,以便例如myscript -a 1 -b 2
使我能够获取值,并且myscript -xyz
也可以工作。我该如何移植(在编译器之间)?
你可以试试看unix-options
。
(ql:quickload :unix-options)
(defpackage :test
(:use :cl)
(:import-from :unix-options
:¶meters
:&free
:with-cli-options))
您可能想要使用:use
该软件包,但是如果您想从中导入符号,请不要忘记&free
和¶meters
。该库定义了一个getopt
与传统getopt
实用程序相似的功能。但它也定义了with-cli-options
,这有点困难。
¶meters
定义参数后的符号,必须后跟一个值;&free
例如:
(in-package :test)
(defun my-program (&rest cli-args)
(with-cli-options (cli-args)
(x y z ¶meters a b &free other)
(list x y z a b other))))
在这里,我定义了程序的入口点。在实际程序中,您可以将第一个列表保留为空,如下所示:
(with-cli-options () <bindings> <body>)
...,然后将从Lisp实现的实际命令行参数中获取选项。您还可以调用(uiop:command-line-arguments)
必须具有完整的命令行,该命令行似乎支持更多的实现,并且将程序名称作为第一个元素。上面的功能允许我测试解析器的行为。请注意,例如,短选项可以分开或合并:
(my-program "-xyz" "-a" "2" "-b" "3" "--" "something")
=> (T T T "2" "3" ("something"))
(my-program "-x" "-y" "-z" "-a" "2" "-b" "3" "--" "something")
=> (T T T "2" "3" ("something"))
请注意声明为参数但未提供实际值的选项(或者可能是,情况不明确):
(my-program "-a" "-b")
=> (NIL NIL NIL "-b" NIL NIL)
有针对未知参数的警告:
(ignore-errors (my-program "-w"))
; WARNING: Invalid option: w
=> (NIL NIL NIL NIL NIL NIL)
有关详细信息,请参阅文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句