【问题标题】:Correct way to include files in Julia-Lang such that updates are considered在 Julia-Lang 中包含文件以考虑更新的正确方法
【发布时间】:2018-04-24 13:36:20
【问题描述】:

我承认对 Julia 不熟悉。但是,通过查看各种文档,我找不到我(可能非常简单)问题的适当答案。

我从 Matlab 中了解到的

考虑文件夹src/ 中的两个文件,分别称为main.manotherfunc.m

function main
 anotherfunc(0)
end

function anotherfunc(x)
 disp(sin(x))
end

我会在命令窗口中运行 main 并查看所需的结果 (=0)。现在,也许我改变主意并更喜欢

function otherfunc(x)
 disp(cos(x))
end

我再次运行main 并看到1

我对 Julia 的不了解 如何做完全相同的事情。 我尝试了两种我认为可行的方法。

1)

文件是anotherfunc.jl:

function anotherfunc(x)
 print(sin(x))
end

和(在同一目录中)main.jl:

function main()
 anotherfunc(0)
end

现在我在终端启动julia并写

julia> include("anotherfunc.jl")
anotherfunc (generic function with 1 method)

julia> include("main.jl")
main (generic function with 1 method)

julia> main()
0.0

很好。现在我将sin 更改为cos 并得到

julia> main()
0.0

这并不让我吃惊,我知道我需要另一个include,即

julia> include("anotherfunc.jl")
anotherfunc (generic function with 1 method)

julia> main()
1.0

所以这可行,但似乎很容易出错,我以后会忘记包含。

2) 我以为我会很聪明并写作

  function main
     include("anotherfunc.jl")
     anotherfunc(0)
    end

但是关闭julia并重新启动它会给出

julia> main()
ERROR: MethodError: no method matching anotherfunc(::Int64)
The applicable method may be too new: running in world age 21834, while current world is 21835.
Closest candidates are:
  anotherfunc(::Any) at /some/path/anotherfunc.jl:2 (method too new to be called from this world context.)
Stacktrace:
 [1] main() at /some/path/main.jl:4

这显然是错误的。

总结:我不知道处理拆分为多个文件的代码和开发过程中的更改的最佳程序。

【问题讨论】:

标签: julia


【解决方案1】:

我认为最简单的方法是使用Modules 而不是include 和包Revise

通过调用`Pkg.add("Revise")安装Revise.jl

我们在您的工作目录或其他目录中的MyModule.jl 中有以下Module

module MyModule

export anotherfunc

function anotherfunc(x)
    display(sin(x))
end

end

首先,确保存储模块的目录位于您的LOAD_PATH 中。默认情况下,Julia 的工作目录不会添加到LOAD_PATH,因此如果您将模块放在工作目录中,则调用push!(LOAD_PATH, pwd()),否则调用push!(LOAD_PATH, "/path/to/your/module")。您可以将此代码添加到您的 .juliarc 文件中,以免为您运行的每个 julia 实例调用此代码。

现在我们有了以下主文件。

using Revise # must come before your module is loaded.
using MyModule

anotherfunc(0)

现在更改您的文件MyModule.jl,使anotherfunc 使用cos 而不是sin,然后查看结果。

我建议你阅读https://docs.julialang.org/en/stable/manual/modules/https://github.com/timholy/Revise.jl

【讨论】:

  • 感谢您的帮助!如果anotherfunc 相当长并且我不想将代码放入MyModule 本身,我会怎么做?也许我也想把anotherfunc2anotherfunc3 放在那里,那样会变得很乱,不是吗?或者我可以将include("...") 放入模块中吗?
  • 是的,您可以这样做。即使您更改了模块中包含的文件,Revise 也会检测到更改。当检测到模块(或模块中包含的文件)发生更改时,您将看到警告。
猜你喜欢
  • 2021-08-15
  • 2020-07-31
  • 2014-10-15
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
相关资源
最近更新 更多