Access command line arguments in Julia
Ah, more web-searching led to the right answer. The keyword ARGS::Array{ASCIIString}
holds command line arguments
Here is a simple example
# cli.jl
print(map(x->string(x, x), ARGS)) # Concatenate each arg onto itself and print
Lets test it at the command line:
$ julia cli.jl a b c
aa
bb
cc
https://docs.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getcommandlinea
In the case that you really need the exact args that came to julia including the -e
, there is a workaround for Windows. Looking at /proc/PID/cmdline
you can extract it linux. Mac doesn't have the same /proc
option, so asking ps
works nicely.
if Sys.iswindows()
mycmd = unsafe_string(ccall(:GetCommandLineA, Cstring, ()))
elseif Sys.isapple()
mycmd = strip(read(`/bin/ps -p $(getpid()) -o command=`, String))
elseif Sys.isunix()
mycmd = replace(read(joinpath("/", "proc", string(getpid()), "cmdline"), String), "\x00"=>" ")
else
mycmd = string(Base.julia_cmd()) * join(map(x->" " * x, ARGS))
end
But typical use cases you only need to look at ARGS
.
A simpler example:
#printargs.jl
println(ARGS[2]);
Run it as
julia printargs.jl a b c d
b
Note that the array index starts from 1 and NOT 0. Thus ARGS[2] prints b and not c as in case of many other programming languages.
julia> Pkg.add("ArgParse")
Docs at https://argparsejl.readthedocs.io/en/latest/argparse.html