我刚开始使用 Clojure(来自 Ruby),我想构建一个带有命令行界面的小应用程序。如何处理 CL 的输入/输出?
我注意到有一个 clojure.contrib.command-line,但文档很少。
我刚开始使用 Clojure(来自 Ruby),我想构建一个带有命令行界面的小应用程序。如何处理 CL 的输入/输出?
我注意到有一个 clojure.contrib.command-line,但文档很少。
这是使用其with-command-line
宏的示例。下面的代码指定了一个带有 main 方法的普通类,该方法只打印出其命令行参数的值。
(ns cmd-line-demo
(:gen-class)
(:use clojure.contrib.command-line))
(defn -main [& args]
(with-command-line args
"Command line demo"
[[foo "This is the description for foo" 1]
[bar "This is the description for bar" 2]
[boolean? b? "This is a boolean flag."]
remaining]
(println "foo: " foo)
(println "bar: " bar)
(println "boolean?: " boolean?)
(println "remaining: " remaining)))
在 REPL 编译类:
user> (compile 'cmd-line-demo)
cmd-line-demo
1) 不使用命令行参数执行将导致显示帮助信息。帮助信息也可以用--help
或-h
标志显示。请注意,帮助信息是从您的 cmdspec 自动生成的。
$ java -classpath . cmd_line_demo
Command line demo
Options
--foo <arg> This is the description for foo [default 1]
--bar <arg> This is the description for bar [default 2]
--boolean, -b This is a boolean flag.
2) 未指定的参数接收在 cmdspec 绑定中指定的默认值。例如,bar
默认值为2
.
$ java -classpath . cmd_line_demo --foo "changed value"
foo: changed value
bar: 2
boolean?: nil
remaining: []
3) 布尔标志由后缀“?”表示 在 cmdspec 中。请注意,标志本身不包括“?” 作为其名称的一部分。
$ java -classpath . cmd_line_demo -boolean
foo: 1
bar: 2
boolean?: true
remaining: []
4) 另请注意,您可以通过在 cmdspec 中指定多个符号来指定标志别名。我已经用boolean?
和b?
标志做到了这一点。
5)最后,我已经指定remaining
捕获所有剩余的参数,但没有关联的标志。
$ java -classpath . cmd_line_demo -foo test file1 file2 file3
foo: test
bar: 2
boolean?: nil
remaining: [file1 file2 file3]
旧的 clojure.contrib.command-line 已替换为 tools.cli。
https://github.com/clojure/tools.cli
tools.cli 曾经被称为 clargon。以下是两篇博客文章,它们提供了使用 tools.cli 的示例(简单地将任何对 clargon 的引用替换为 tools.cli。文章已过时)。
我想补充一点,你可以做到
(apply -main *command-line-args*)
下方(defn -main ...)
,使其在解释模式下工作。
在提出这个问题很长时间后,我可以建议在docopt
构建 CLI 界面时使用库。Clojure有一个 -docopt.clj
docopt 基于几十年来在帮助消息和手册页中用于程序接口描述的约定。docopt中的接口描述就是这样一条帮助信息,但是形式化了
因此,您可以同时声明您的界面并记录它——这非常棒,而且很容易做到。
有关更多详细信息,我建议查看http://doopt.org/
还有一个在线应用程序可以检查您的界面http://try.docopt.org/
最后,这是我如何使用 Clojure 库的示例。
也许试试 jark。Jark 是一个在持久 JVM 上运行 clojure 程序的工具。它有一些有用的命令行实用程序。
jark ns load file.clj
jark <namespace>.<function> <args>
jark if cli-json <namespace><function> args