How to run a Julia script from the command line which has package dependencies?

I’m trying to run a Julia script like an executable program from the command line.

$ julia myscript.jl

If this script has dependencies on packages, such as the Distributions package, how can I run such a script from the command line?

This is how I have setup my local environment and installed packages.

(@v1.10) pkg> activate test-env
(test-env)> add Distributions
(test-env)> CTRL^C
> CTRL^D
$ julia myscript.jl
ERROR: LoadError: ArgumentError: Package Distributions not found in current path.
- Run `import Pkg; Pkg.add("Distributions")` to install the Distributions package.

I’m not sure how to “connect” the two together?

julia --project=test-env myscript.jl
3 Likes

Another option is to start the script with

using Pkg
Pkg.activate(@__DIR__)
Pkg.instantiate()

Compared to using the --project flag this has the disadvantage that the global environment is initially active and if you have a startup file which loads packages, you could get wrong versions loaded before activating the script environment.

The big advantage obviously, is that you don’t have to type the --project specification every time you run the script.

Notes:

  • Line 2 assumes that the environment is in the same directory as the script. If that is not the case, you need to adjust it accordingly.
  • Line 3 mostly matters if you, or someone else, wants to run the script on another computer and just have it work, even if the dependencies have not been previously installed.
1 Like

To check I understand this correctly - you would add these three lines at the top of a Julia script and then call that script from the command line as normal?

Yes.