如何定义project.clj使得lein run和lein repl都能正常工作?

11

我刚接触Clojure,并不太明白如何编写我的project.clj文件,使得它同时适用于lein repllein run。这是我的代码(完整路径:~/my-project/project.clj):

(defproject my-project "1.0.0-SNAPSHOT"
  :description "FIXME: write description"
  :dependencies [[org.clojure/clojure "1.3.0"]]
  :main my-project.core/hello
)

然后我有我的~/my-project/src/my_project/core.clj文件。

(ns my-project.core)

(defn hello []
  (println "Hello world!")
)

lein run工作正常,但在运行lein repl时出现FileNotFoundException

~/my-project$ lein run
Hello world!
~/my-project$ lein repl
REPL started; server listening on localhost port 42144
FileNotFoundException Could not locate hello__init.class or hello.clj on classpath:   clojure.lang.RT.load (RT.java:430)
clojure.core=>

我该如何编辑project.clj来解决这个问题?或者我需要以不同的方式调用lein repl吗?谢谢。

编辑:尝试了lein deplein compile,但仍出现相同的错误。

~/my-project$ lein version
Leiningen 1.7.1 on Java 1.6.0_27 OpenJDK Client VM
~/my-project$ lein deps
Copying 1 file to /home/yasin/Programming/Clojure/my-project/lib
~/my-project$ lein compile
No namespaces to :aot compile listed in project.clj.
~/my-project$ lein repl
REPL started; server listening on localhost port 41945
FileNotFoundException Could not locate hello__init.class or hello.clj on classpath:   clojure.lang.RT.load (RT.java:430)

看起来你正在使用 lein 1,对吧?(你可以通过 lein version 命令进行确认)。如果是这样的话,我认为你应该先运行 lein depslein compile 命令,然后再尝试使用 lein repl - ivant
谢谢,但还是不行...我已经编辑了问题并提供了更多细节。 - m0skit0
如果你是Clojure的新手,使用lein2。现在没有理由使用lein 1.7,特别是如果你刚开始学习。 - Cubic
@Cubic 谢谢。我甚至不知道有 lein2 存在。我刚从 Ubuntu 软件库中安装了它。 - m0skit0
@m0skit0 我建议你跳过那些你直接使用的东西。虽然并非所有软件包都是如此,但很多软件包已经相当陈旧了。 - Cubic
1个回答

18

你可以尝试更改core.clj文件以使其正常工作:

(ns my-project.core
  (:gen-class))

(defn hello []
  (println "Hello world!"))

(defn -main []
  (hello))

并编辑project.clj为:

(defproject my-project "1.0.0-SNAPSHOT"
  :description "FIXME: write description"
  :dependencies [[org.clojure/clojure "1.3.0"]]
  :main my-project.core)

(:gen-class)指示编译器为该命名空间生成Java类,project.clj文件中的:main指令会告诉lein run在该类上运行主方法,该方法由-main给出。我不确定为什么lein repl无法找到my-project.core/hello,但我对Leiningen内部了解不多。


它可以工作。我只需要定义一个-main函数让它工作,并将:main更改为:main my-project.core,就像你建议的那样。顺便说一下,你在core.clj的末尾忘记了一个括号,我已经修复了 :) - m0skit0
1
为什么Leiningen需要在JAR文件中有main函数,实际上是为了启动REPL? - matanster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接