Gangmax Blog

自由之思想,独立之精神

How to Run Clj File Using Leiningen

| Comments

From here and here.

“lein-exec” is a Leiningen plugin to execute Clojure scripts. Install it as a global plugin in “~/.lein/profiles.clj”:

1
{:user {:plugins [[lein-exec "0.3.3"]]}}

Then run “lein”, lein will fetch the artifacts and install it. Then an “exec” item can be used in the “lein” command:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ lein
Leiningen is a tool for working with Clojure projects.

Several tasks are available:
check               Check syntax and warn on reflection.
classpath           Write the classpath of the current project to output-file.
clean               Remove all files from paths in project's clean-targets.
compile             Compile Clojure source into .class files.
deploy              Deploy jar and pom to remote repository.
deps                Show details about dependencies.
do                  Higher-order task to perform other tasks in succession.
exec                Execute Clojure S-expresions from command-line or scripts.
help                Display a list of tasks or help for a given task or subtask.
...

Now you can use “lein exec” to execute either S-expressions or clj script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$ lein help exec
Execute Clojure S-expresions from command-line or scripts.

Usage:
    lein exec [-p]
    lein exec -e[p] <string-s-expr>
    lein exec [-p] <script-path> [args]

When invoked without args it reads S-expressions from STDIN and evaluates them.
When only option `-p` is specified, it evaluates STDIN in project context.

-e  evaluates the following string as an S-expression
-ep evaluates the following string as an S-expression in project (w/classpath)
-p  indicates the script should be evaluated in project (with classpath)

Examples:
    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

Optional args after script-path are bound to clojure.core/*command-line-args*
Executable Clojure script files should have the following on the first line:
#!/usr/bin/env lein exec

Arguments: ([& args])

Comments