How to PackageCompile ArgParse

I’ve been trying to get the same thing working. I think you’re better off setting it up as a project.

I’m not really sure if this setup is ideal, but it at least works.

First create your project.

julia -e 'using Pkg; Pkg.generate("MyProj")'
cd MyProj

You’ll need to setup a precompile script (see here for details on precompiling). Unfortunately you can’t really run your main script as your precompile script since ArgParse errors out when passed invalid arguments. So you either need to not run parse_args or create some sort of noop command.

So your main app function will look something like this.

/MyProj/src/MyProj.jl

module MyProj

export run

using ArgParse

function run(parseargs::Bool)
    s = ArgParseSettings()

    @add_arg_table s begin
        "arg1"
            help = "a positional argument"
            required = true
    end

    # don't run parse_args when precompiling.
    # alternatively you could just create a noop command
    # and pass ARGS to the run function.
    if !parseargs
        return
    end

    args = parse_args(ARGS, s)
    println(args)
end

end # module

/MyProj/app.jl

using MyProj
MyProj.run(true)

Now you just create the precompile and sysimage creation scripts.

/MyProj/scripts/precompile.js

using MyProj
MyProj.run(false) # same as app.jl but does not run parse_args()

/MyProj/scripts/create_image.jl

using PackageCompiler
using Pkg
Pkg.activate(".")
create_sysimage([:ArgParse, :MyProj];
    sysimage_path="MyProj.so",
    precompile_execution_file=joinpath(@__DIR__, "precompile.jl")
)

Then to setup the sysimage run the script.

julia scripts/create_image.jl

And then you can run your program

time julia --project=@. -JMyProj.so app.jl arg1 -h

real	0m0.640s
user	0m0.770s
sys	    0m0.110s

See here a complete example.

4 Likes