How can a clojure script recognise it is running as a script?

2 views
Skip to first unread message

Kelvin Ward

unread,
Sep 18, 2009, 6:46:02 AM9/18/09
to Clojure
java -cp clojure.jar clojure.main foo.clj

I'm wondering if the code in foo.clj has anyway to know it is being
executed as a script. In python there's the idiom:

def main(): ...

if __name__ == "__main__":
main()

I can then import the file at the repl and execute main() only if
want. I can also have main called by executing it as a script.

I'm guessing passing a property to the clojure script is the best way
to do this, e.g.:

java -cp clojure.jar -Dclojure.mainscript=foo.clj clojure.main foo.clj

foo.clj:

(defn main []
; ...
)

(if (= (System/getProperty "clojure.mainscript") "foo.clj")
(main))

Any thoughts?

Thanks.

David Nolen

unread,
Sep 18, 2009, 9:57:36 AM9/18/09
to clo...@googlegroups.com
The source itself cannot know the way a Python knows. However you can understand how to achieve pretty much the same effect with the following:

Stuart Sierra

unread,
Sep 18, 2009, 11:45:59 AM9/18/09
to Clojure
On Sep 18, 6:46 am, Kelvin Ward <kelvin.d.w...@googlemail.com> wrote:
> java -cp clojure.jar clojure.main foo.clj
>
> I'm wondering if the code in foo.clj has anyway to know it is being
> executed as a script. In python there's the idiom:

This doesn't exist right now. The closest equivalent is:

(ns my-namespace
(:gen-class))

(defn -main [& args]
(println "I was run at the command line."))

This has been discussed at length before. Clojure isn't really a
scripting language, so it may never support this kind of idiom.

-SS

Kelvin Ward

unread,
Sep 18, 2009, 3:38:21 PM9/18/09
to Clojure
Thanks for the help guys, I'll look at compilation.

ataggart

unread,
Sep 18, 2009, 7:42:38 PM9/18/09
to Clojure
Just for my own edification (not being versed in python), what's the
point of knowing that?

David Nolen

unread,
Sep 18, 2009, 7:56:20 PM9/18/09
to clo...@googlegroups.com
So that you can write python code that can function both as a shell script and as a library transparently.
Reply all
Reply to author
Forward
0 new messages