[ACCEPTED]-How to run .clj file as a script using leningen?-leiningen

Accepted answer
Score: 39

There are several ways with lein repl:

  • Very slow: cat your_file.clj | lein repl
  • Slow: echo '(load-file "your_file.clj")' | lein repl
  • Fast:
    1. lein repl
    2. (load-file "your_file.clj")
    3. repeat 2

0

Score: 27

use lein-exec plugin, example from readme.md (updated 1 with "lein" instead of "lein2")

cat foo.clj | lein exec
lein exec -e '(println "foo" (+ 20 30))'
lein exec -ep "(use 'foo.bar) (pprint (map baz (range 200)))"
lein exec -p script/run-server.clj -p 8088
lein exec ~/common/delete-logs.clj
Score: 8

leiningen can create an 'uberjar' for you 11 with all your dependencies....

lein uberjar

will create 10 a jar for you in the target subdirectory. The 9 jar will contain all the dependencies listed 8 in your project.clj, so you don't need to worry about 7 constructing a complex classpath to invoke 6 your code.

You can reference this uberjar 5 as a single entry in your java classpath 4 in the normal way or, specify a main-class 3 in the project.clj invoke it as an executable jar.

e.g. a 2 project.clj like this:

(defproject clj-scratch "1.0.0-SNAPSHOT"
 :description "FIXME: write description"
 :dependencies [[org.clojure/clojure "1.4.0"]                     
 :main clj-scratch.core)

will invoke the -main function in 1 clj-scratch.core namespace

if you run:

java -jar target/clj-scratch-1.0.0-SNAPSHOT-standalone.jar
Score: 0

I like to use inlein for that.

#!/usr/bin/env inlein

'{:dependencies [[org.clojure/clojure "1.8.0"]
                 [com.hypirion/primes "0.2.1"]]}

(require '[com.hypirion.primes :as p])

(when-not (first *command-line-args*)
  (println "Usage:" (System/getProperty "$0") "prime-number")
  (System/exit 1))

(-> (first *command-line-args*)
    (Long/parseLong)
    (p/get)
    println)

Then just chmod +x script.clj and run 1 it!

Alternatively you can just inlein script.clj my args here as well.

More Related questions