Problem with importing a module after include

Hi,

I am getting this warning after I run include and then import my module
So I created a folder with two julia scripts Mymod.jl and test.jl :

MyMod.jl contains:

module MyMod
x=1
end

And in test.jl :

include("MyMod.jl")
import .MyMod
MyMod.x

After the import I get the following:
WARNING: could not import Main.MyMod into Main
And I can’t use MyMod.x

If I try “using”:

ERROR: UndefVarError: MyMod not defined
Stacktrace:
 [1] include_string(::Function, ::Module, ::String, ::String) at ./loading.jl:1088

I started Julia from the same directory where I store the two scripts.

include("MyMod.jl")
MyMod.x

is enough.

For using MyMod, you must put the .jl in

ENV["JULIA_LOAD_PATH"]
1 Like

Thanks
I tried only writing include('MyMod.jl")
and then MyMod.x and it didn’t work:

ERROR: UndefVarError: MyMod not defined
Stacktrace:
 [1] top-level scope at REPL[2]:1

I also tried with writing first:

push!(LOAD_PATH, pwd())

and then:

using MyMod

and it didn’t work :frowning: :

using MyMod
[ Info: Precompiling MyMod [top-level]
WARNING: --output requested, but no modules defined during run
┌ Warning: The call to compilecache failed to create a usable precompiled cache file for MyMod [top-level]
│   exception = ArgumentError: Invalid header in cache file /home/maah/.julia/compiled/v1.5/MyMod.ji.
└ @ Base loading.jl:1042
ERROR: KeyError: key MyMod [top-level] not found
Stacktrace:
 [1] getindex at ./dict.jl:467 [inlined]
 [2] root_module at ./loading.jl:968 [inlined]
 [3] require(::Base.PkgId) at ./loading.jl:934
 [4] require(::Module, ::Symbol) at ./loading.jl:923
julia> versioninfo()
Julia Version 1.5.0
Commit 96786e22cc (2020-08-01 23:44 UTC)
Platform Info:
  OS: Windows (x86_64-w64-mingw32)
  CPU: Intel(R) Core(TM) i5-8300H CPU @ 2.30GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-9.0.1 (ORCJIT, skylake)
Environment:
  JULIA_EDITOR = "C:\Users\GNSS-BSAR\AppData\Local\atom\app-1.49.0\atom.exe"  -a
  JULIA_HOME = C:\Users\GNSS-BSAR\AppData\Local\Programs\Julia 1.5.0
  JULIA_LOAD_PATH = G:\Julia\ToolBox;
  JULIA_NUM_THREADS = 4
  JULIA_PKG_SERVER = https://cn-northeast.pkg.juliacn.com/

julia> pwd()
"G:\\Julia\\TestScript"

julia> pwd() |> readdir
1-element Array{String,1}:
 "MyMod.jl"

julia> MyMod
ERROR: UndefVarError: MyMod not defined

julia> include("MyMod.jl")
Main.MyMod

julia> MyMod
Main.MyMod

julia> MyMod.x
1

The code above works on my laptop.
Strange bug, have you checked the pwd()'s result?

1 Like

You don’t need to edit any paths to get relative import using .MyMod works.

All error messages, especially the warning you got with using MyMod points to that you didn’t actually have the content you expect in your MyMod.jl. Did you save the file, and saved it to the right path?

2 Likes