在 lein repl 中传递命令行参数

Passing command line arguments in lein repl

我有一个接受命令行参数的主函数声明

(defn -main [& args]
    (let [options (cli/parse-opts args [["-k", "--key KEY","Secret key"]
                                        ["-u", "--user USER", "User name"]])]
        (println user key)))

我正在尝试在 lein repl 中加载它进行调试,但无法弄清楚如何通过 REPL 传递参数。

我尝试了多种方法通过 repl 传递参数,包括

(-main "key-val" "user-val")(打印 nil nil

(-main ("key-val" "user-val"))(打印 nil nil

我尝试了多次失败的尝试,并尝试传递抛出转换错误的列表或向量。

首先,请注意 userkey 未绑定到 parse-opts 的结果。 parse-opts returns a map 这些选项在 :options 项下。 让我们绑定结果如下:

(defn -main [& args]
  (let [options (parse-opts args [["-k", "--key KEY","Secret key"]
                                  ["-u", "--user USER", "User name"]])
        user (get-in options [:options :user])
        key  (get-in options [:options :key])]
    (println user key)))

您的 parse-opts 调用指定您期望 命名参数 ,即 options解析。来自 REPL 的如下调用:

(-main "-k a" "-u b") ; prints "b a"

请注意,如果您指定位置参数,它们将位于键 :arguments 下。更改示例以打印绑定到选项 ((println options)) 的值后,您的示例调用将像这样工作:

(-main "key-val" "user-val") ; {:arguments [key-val user-val] :options {} ...}

所以调用时没有选项,也就是说,没有指定命名参数

你已经用键“-k”和“-u”定义了参数,但还没有将键传递给函数,所以解析器将无法猜测你期望它得到什么。工作版本是这样的:

user> (defn -main [& args]
        (let [options (cli/parse-opts args [["-k", "--key KEY","Secret key"]
                                            ["-u", "--user USER", "User name"]])
              {:keys [key user]} (:options options)]
          [key user]))
#'user/-main

user> (-main "-k" "key-val" "-u" "user-val")
;;=> ["key-val" "user-val"]

user> (-main "--key" "key-val" "--user" "user-val")
;;=> ["key-val" "user-val"]