【问题标题】:*ns* unexpectedly evaluate to 'user' namespace using 'lein run', but not when using 'lein repl'*ns* 使用 'lein run' 意外评估为 'user' 命名空间,但在使用 'lein repl' 时却没有
【发布时间】:2020-09-26 11:29:47
【问题描述】:

我正在尝试获取与实际运行的代码关联的命名空间。

我使用“lein new app test”创建了一个模板项目:

(ns test.core
  (:gen-class))

(defn -main
  [& args]
  (println (ns-name *ns*)))

使用 repl 时,*ns* 计算结果为 test.core:

echo "(-main)" | lein repl
nREPL server started on port 37435 on host 127.0.0.1 - nrepl://127.0.0.1:37435
REPL-y 0.4.4, nREPL 0.7.0
Clojure 1.10.1
OpenJDK 64-Bit Server VM 1.8.0_265-b01
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

test.core=> (-main)
test.core
nil
test.core=> Bye for now!

但是当使用 lein run 时,我得到了用户命名空间:

lein run
user

为什么会有这样的行为? 如何获取 repl 中的一段代码的命名空间?

【问题讨论】:

标签: clojure


【解决方案1】:

需要注意的几点:

  • *ns* 绑定到计算表达式的命名空间
  • user 是默认命名空间
  • 当您从user 命名空间调用(test.core/-main) 时,*ns* 绑定到user,而不是test.core

如果您想打印定义-main 的命名空间,您可以使用顶级表达式:

(ns test.core)
(def current-ns *ns*)
(defn -main [& args]
  (println (ns-name current-ns)))

或使用 var 元数据:

(ns test.core)
(defn -main [& args]
  (println (ns-name (:ns (meta #'-main)))))

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    相关资源
    最近更新 更多