从 Julia 1.0 中特定目录中的文件导入模块和函数

Import modules and functions from a file in a specific directory in Julia 1.0

假设我有一个文件 File.jl,其中有一个模块 MyModule,其中包含函数 foobar。在与模块文件相同的目录中,我有一个脚本Script.jl,我想在脚本中使用MyModule中的函数。

如何做这件事?

您将文件包含在模块定义中并调用脚本文件中的函数:

include(joinpath(@__DIR__,"File.jl"))
MyModule.foo()
MyModule.bar()
# or just foor() and bar() if MyModule exports those functions

@__DIR__扩展到脚本文件的目录,见

help?> @__DIR__
  @__DIR__ -> AbstractString

  Expand to a string with the absolute path to the directory of the file containing the macrocall. Return the current working directory if run from a REPL or if evaluated by julia -e <expr>.

为了找到不在标准 LOAD_PATH 中的模块并能够导入它们,您需要显式更新当前文件夹的 LOAD_PATH 变量

push!( LOAD_PATH, "./" )

然后你就可以适当地导入模块了。

请注意,如果文件名为 File.jl 并定义了模块 MyModule,您应该导入的是 import MyModule,而不是 import File。这种情况下一般建议文件名与定义模块同名,避免混淆。

另请注意,正如@crstnbr 上面提到的,您也可以通过 'including' 将文件的内容简单地 'dump' 到当前会话中;但是请注意,这只是当场创建模块,因此不会接受任何预编译指令等。


一些相关的问题/答案(免责声明:由我提供)您可能会觉得有用: