How to import custom module in julia

I have a module that I wrote here:

# Hello.jl
module Hello
    function foo
        return 1
    end
end

and

# Main.jl
using Hello
foo()

When I run the module Main:

$ julia ./Main.jl

I get this error:

ERROR: LoadError: ArgumentError: Hello not found in path
 in require at ./loading.jl:249
 in include at ./boot.jl:261
 in include_from_node1 at ./loading.jl:320
 in process_options at ./client.jl:280
 in _start at ./client.jl:378
while loading /Main.jl, in expression starting on line 1
+4
source share
5 answers

You have include("./Hello.jl")tousing Hello

+6
source

There were short answers, but I would like to provide a more complete answer, if possible.

When you start using MyModule, Julia searches for it only in the list of directories known as yours LOAD_PATH. If you type LOAD_PATHin Julia REPL, you will get the following:

2-element Array{ByteString,1}:
 "/Applications/Julia-0.4.5.app/Contents/Resources/julia/local/share/julia/site/v0.4"
 "/Applications/Julia-0.4.5.app/Contents/Resources/julia/share/julia/site/v0.4"

, using Hello. , , Hello LOAD_PATH, .

, .

julia> include("./src/Hello.jl")

, using Hello , . , , . , , include() , LOAD_PATH.

LOAD_PATH

LOAD_PATH , , Julia LOAD_PATH. LOAD_PATH. Julia , import using.

- .basrc, .profile, .zshrc.

export JULIA_LOAD_PATH="/path/to/module/storage/folder"

, .

julia> LOAD_PATH

3-element Array{ByteString,1}:
 "/path/to/module/storage/folder"
 "/Applications/Julia-0.4.5.app/Contents/Resources/julia/local/share/julia/site/v0.4"
 "/Applications/Julia-0.4.5.app/Contents/Resources/julia/share/julia/site/v0.4"

using Hello, Julia ( /path/to/module/storage/folder.

Julia.

+7

张 实 is , , include REPL. , LOAD_PATH. , , , . ( docs: push!(LOAD_PATH, "/Path/To/My/Module/"), , )

, , include , include, . , , , MyModule . include , MyModule, , . , , MyModule (, ), .

, , :

types.jl

module TypeModule
struct A end
export A
end

a_function.jl

include("types.jl")
module AFunctionModule
using TypeModule
function takes_a(a::A)
    println("Took A!")
end
export takes_a
end

function_caller.jl

include("a_function.jl")
include("types.jl")
using TypeModule, AFunctionModule
my_a = A()
takes_a(my_a)

julia function_caller.jl, MethodError: no method matching takes_a(::TypeModule.A). , A, function_caller.jl, , a_function.jl. "" , function_caller.jl( include("types.jl") function_caller.jl! !). , b_function.jl, , TypeModule? - . LOAD_PATH, .

+2

If you want to access the foo function when importing a module using it, you need to add export foo to the module header.

0
source

If you explicitly download the file ( include("./Hello.jl")), Julia looks for module files in the directories defined in the LOAD_PATH variable.

See this page .

0
source

All Articles