I'm assuming by run as a script you mean via clojure.main as follows:
java -cp clojure.jar clojure.main /path/to/myscript.clj
If so then there is a simple technique: put all the library functions in a separate namespace like mylibrary.clj
. Then myscript.clj can use/require this library, as can your other code. But the specific functions in myscript.clj will only get called when it is run as a script.
As a bonus, this also gives you a good project structure, as you don't want script-specific code mixed in with your general library functions.
EDIT:
I don't think there is a robust within Clojure itself way to determine whether a single file was launched as a script or loaded as a library - from Clojure's perspective, there is no difference between the two (it all gets loaded in the same way via Compiler.load(...) in the Clojure source for anyone interested).
Options if you really want to detect the manner of the launch:
- Write a main class in Java which sets a static flag then launched the Clojure script. You can easily test this flag from Clojure.
- Use AOT compilation to implement a Clojure main class which sets a flag
- Use *command-line-args* to indicate script usage. You'll need to pass an extra parameter like "script" on the command line.
- Use a platform-specific method to determine the command line (e.g. from the environment variables in Windows)
- Use the --eval option in the clojure.main command line to load your clj file and launch a specific function that represents your script. This function can then set a script-specific flag if needed
- Use one of the methods for detecting the Java main class at runtime