Julia的目錄使用方法
1 使用joinpath
和@__DIR__
假如我們有個包 Mypackage
,有如下結(jié)構(gòu)
Mypackage/test/test.jl
Mypackage/src/mymoudel.jl
那么在test.jl
中include mymoudel.jl
時丽焊,需要在test.jl
中寫入
include(joinpath(@__DIR__, "..", "src", "mymoudel.jl"))
其中,..
表示上一級目錄滔以。如果三個點...
表示上上級目錄趾娃。一個點.
表示當(dāng)前目錄,可以不寫痛侍。@__DIR__
返回當(dāng)前源代碼所在目錄曹步。
2 直接使用相對目錄
仍然采用上一節(jié)的例子宪彩。
include("../src/mymodule.jl")
此處,../
表示當(dāng)前目錄的上一級目錄讲婚。./
表示當(dāng)前目錄尿孔,只有一個點也可以忽略不寫,用/
磺樱。
3 多文件的例子
假定有如下目錄的項目
content.png
"文件mymodule.jl"
module mymodule
export p, fun1, Point
p = 3.0
include("../functions/fun1.jl")
include("../functions/fun2.jl")
struct Point
x::Float64
y::Float64
Point(x, y) = new(convert(Float64,x), convert(Float64,y))
end
end
"文件fun2.jl"
function fun1(x, y)
return x + y
end
"文件fun2.jl"
function fun2(x, y)
return x - y
end
test1
test1.jl
內(nèi)的代碼為:
include(joinpath(@__DIR__, "..", "modules", "mymodule.jl"))
using .mymodule
f1 = fun1(1, 2)
f2 = mymodule.fun2(5, 6)
c = mymodule.p
mp = mymodule.Point(4,5)
運行test1.jl
可以加載mymodule
纳猫,而mymodule
又調(diào)用了函數(shù)fun1
和fun2
。這里在創(chuàng)建mymodule
的時候竹捉,沒有把fun1
和fun2
寫在mymodule.jl
文件內(nèi)芜辕,可以避免fun1
和fun2
文件內(nèi)容太長,不利于閱讀块差。
test2
test2.jl
內(nèi)的代碼為:
include("../functions/fun1.jl")
include("../modules/mymodule.jl")
import .mymodule
a = fun1(5, 6)
b = mymodule.Point(6, 8)
c = mymodule.fun2(8, 90)
d = mymodule.fun1(66, 88)
這里fun1
是直接從fun1.jl
內(nèi)讀取的函數(shù)侵续,使用mymodule
內(nèi)的fun1
使用mymodule.fun1
得以區(qū)分。