Introducing Julia/Modules and packages

维基教科书,自由的教学读本


« Introducing Julia
Modules and packages
»
Metaprogramming DataFrames

模块与包[编辑]

Julia代码被组织成文件、模块和包。Julia 代码文件使用 .jl 文件扩展名。

模块[编辑]

相关函数和其他定义可以组合在一起 并存储在 模块 中。模块的结构如下:

module MyModule
 
end

在这些行之间,可以放入函数、类型定义、常量等等。


一个或多个模块 可以存储在一个 中,这些模块使用 git 版本控制系统进行管理。大多数 Julia 包 (包括官方的) 都存储在GitHub上,按照惯例,每个Julia包都以“.jl”后缀命名。


安装模块[编辑]

要在您自己的机器上使用官方的 (注册的) Julia 模块,您需要从 GitHub 主站点下载并安装包含该模块的包。在 http://pkg.julialang.org 上有一个很大的官方软件包列表。

【译者注:该网站自 2018-08-05 后不再更新, 建议在 https://juliaobserver.com/ 中查找相关包】

To download and install a package, you can use Julia's package manager. Start by typing a right bracket ] into the REPL to enter the package manager, then use the add command. You don't have to use quotes or the ".jl" suffix.

julia> ]
(v1.0) pkg> add Calculus
... messages
(v1.0) pkg>

(If you are not directly connected to the internet, you need to give the name of a proxy before calling the package installer.)

The (v1.0) in the prompt tells you that you're working in the default project, "v1.0", in ~/.julia/environments/.

If you want to update the packages you have, use the up command:

(v1.0) pkg> up
... messages
(v1.0) pkg>

For more information about Julia's powerful package management system, refer to the extensive documentation.

To leave the package manager mode, press the Backspace/Delete key.

Using modules 使用模块[编辑]

After installation, to start using functions and definitions from the module, you tell Julia to make the code available to your current session, with the using or import statements, which accept the names of one or more installed modules:

julia> using Calculus

julia>

On success, all the definitions in the Calculus module are available for use. If the definitions inside Calculus were exported by the module's author, you can use them without the module name as prefix (because we used using):

julia> derivative(sin, pi/2)
0.0

If the package author(s) don't export the definitions, or if we use import rather than using, you can still access them, but you have to type the module name as a prefix:

julia> Calculus.derivative(sin, pi/2)
0.0

but that's unnecessary in this example, as we've seen.

When you write your own modules, the functions that you choose to export can be used without the module name as prefix. Those that you don't export can still be used, but only if they are prefixed with the module name. For example, in the module called MyCoolModule, the mycoolfunction() was exported. So the prefix is optional:

julia> using MyCoolModule

julia> MyCoolModule.mycoolfunction()
"this is my cool function"

julia> mycoolfunction()
"this is my cool function"

Inside the module, this function was exported, using the export statement:

module MyCoolModule
export mycoolfunction

function mycoolfunction()
   println("this is my cool function")
end

end

using 和 import[编辑]

importusing 相似, 但在一些地方不同。例如 如何访问模块中的函数。下面是一个 有两个函数的模块,其中一个函数被导出(export):

module MyModule
export mycoolfunction

function mycoolfunction()
   println("this is my cool function")
end

function mysecretfunction()
   println("this is my secret function")
end

end

使用 import 来导入模块:

julia> import MyModule

julia> mycoolfunction()
ERROR: mycoolfunction not defined

julia> MyModule.mycoolfunction()
"this is my cool function"

注意 mycoolfunction() 函数 只有 在使用模块前缀时才能访问。这是因为 MyModule 模块是通过 import 加载的,而不是用 using.

类似地,对于 mysecretfunction() 函数:

julia> mysecretfunction()
ERROR: mysecretfunction not defined

julia> MyModule.mysecretfunction()
this is my secret function

(用 using)可以指定一系列模块:

julia> using Color, Calculus, Cairo

另一个重要的区别是 想要修改或扩展另一个模块中的函数时。不能使用 using,必须 import 特定的函数。


Include[编辑]

如果要使用模块中未包含的其他文件中的代码,请使用 include() 函数。

这将会在当前模块中执行其他文件的内容,根据相对路径对该文件进行搜索。就像你把代码贴进去一样。

这对于从许多较小的文件中构建代码非常有用。

Julia如何查找一个模块?[编辑]

Julia 在 LOAD_PATH 变量中定义的目录中查找模块文件。

julia> LOAD_PATH
3-element Array{String,1}:
 "@"      
 "@v#.#"  
 "@stdlib"

要使其在查找其他路径,请使用 push! 添加内容:

julia> push!(LOAD_PATH, "/Users/me/myjuliaprojects")
3-element Array{String,1}:
 "@"      
 "@v#.#"  
 "@stdlib"                                                     
 "/Users/me/myjuliaprojects"      

And, since you don't want to do this every single time you run Julia, put this line into your startup file ~/.julia/config/ startup.jl, which runs each time you start an interactive Julia session.

Julia looks for files in those directories in the form of a package with the structure:

ModuleName/src/file.jl

Or, if not in Package form (see below), it will look for a filename that matches the name of your module:

julia> using MyModule

and this would look in the LOAD_PATH for a file called MyModule.jl and load the module contained in that file.

Packages[编辑]

要查看已安装的所有软件包,请执行以下操作:

julia> ]
(v1.0) pkg> status
   Status `~/.julia/environments/v1.0/Project.toml`
 [c7932e45] AstroLib v0.3.0
 [9e28174c] BinDeps v0.8.8
 [159f3aea] Cairo v0.5.2
 [49dc2e85] Calculus v0.4.0
 [3da002f7] ColorTypes v0.6.7
 [5ae59095] Colors v0.8.2
 [861a8166] Combinatorics v0.6.0
 [34da2185] Compat v0.68.0
 [864edb3b] DataStructures v0.8.3
 [5789e2e9] FileIO v0.9.0
 [53c48c17] FixedPointNumbers v0.4.6
 [28b8d3ca] GR v0.31.0
 [a2bd30eb] Graphics v0.3.0
 [9fb69e20] Hiccup v0.2.1
 [a4bce56a] Iterators v0.3.1
 [e5e0dc1b] Juno v0.4.1
 ... messages 
 ...
(v1.0) pkg> 

包的结构[编辑]

Julia 用 git 来组织和管理包。按照惯例,所有包都存储在git储存库中,后缀为“.jl”。因此 Calculus 包存储在名为 Calculus.jl 的 Git 存储库中。以下是根据磁盘上的文件组织Calculus软件包的方式:

Calculus.jl/                                       # this is the main package directory for the Calculus package
  src/                                             # this is the subdirectory containing the source
    Calculus.jl                                    # this is the main file - notice the capital letter
      module Calculus                              # inside this file, declare the module name
        import Base.ctranspose                     # and import other packages
        export derivative, check_gradient,         # export some of the functions defined in this package
        ...
        include("derivative.jl")                   # include the contents of other files in the module
        include("check_derivative.jl")             
        include("integrate.jl")
      end                                          # end of Calculus.jl file
    derivative.jl                                  # this file contains code for working with derivatives, 
      function derivative()                        #      and is included by Calculus.jl
        ...
      end
        ...
    check_derivative.jl                            # this file concentrates on derivatives, 
      function check_derivative(f::...)            #      and is included by "include("check_derivative.jl")" in Calculus.jl
        ...
      end
      ...
    integrate.jl                                   # this file concentrates on integration, 
      function adaptive_simpsons_inner(f::Funct   # and is included by Calculus.jl
        ...
      end
      ...
    symbolic.jl                                    # concentrates on symbolic matters; included by Calculus.jl
      export processExpr, BasicVariable, ...       # these functions are available to users of the module
      import Base.show, ...                        # some Base functions are imported, 
      type BasicVariable <: AbstractVariable       # ... so that more methods can be added to them
        ...
      end
      function process(x::Expr)
        ...
      end
      ...     
  test/                                            # this directory contains the tests for the Calculus module
    runtests.jl                                    # this file runs the tests
      using Calculus                               # obviously the tests use the Calculus module... 
      using Base.Test                              # and the Base.Test module... 
      tests = ["finite_difference", ...            # the test file names are stored as strings... 
      for t in tests
        include("$(t).jl")                         # ... so that they can be evaluated in a loop 
      end
      ...
    finite_difference.jl                           # this file contains tests for finite differences, 
      @test ...                                    # ... its name is included and run by runtests.jl
      ...

标准库[编辑]

Base 模块和 Core 模块在 Julia 中是一直可用的。 Julia 还自带一些标准模块,也叫标准库 stdlib。它们在 Julia 安装时一并安装了,但并没有在 Julia 启动时自动加载。

如果你想用某个标准库,但它没有被自动加载,只需要像加载普通库一样使用 usingimport 加载它就行了。

以下模块是 Julia 1.x 版本附带的标准库(stdlib

Base64 编码、解码 Base64 字符串
CRC32c 计算 CRC-32c 校验和
Dates 处理时间和日期
DelimitedFiles 提供 readdlm()writedlm() 等函数读写分隔符文件
Distributed 与集群上的众多机器一起工作
FileWatching 监测文件和文件夹的改动
Future 实现了一些新功能,它们可能会在后续版本中取代现有的函数
InteractiveUtils 辅助内省(introspection)函数(通常和 REPL 一起加载)
Libdl 动态链接器
LibGit2 Git 库的绑定
LinearAlgebra 线性代数函数
Logging 记录计算的历史
Markdown Markdown 格式转换支持
Mmap 处理内存映射的数组(memory-mapped arrays)
Pkg 管理包的安装与删除
Printf C 风格的 printf 格式化
Profile 性能测试工具
Random 产生随机数
REPL Julia 的交互式命令行工具(REPL)
Serialization 读写 julia 的数据
SHA 提供 SHA 支持
SharedArrays 共享数组
Sockets TCP 套接字支持
SparseArrays 比稠密数组更节约空间的稀疏数组
Statistics 基本的统计函数: std, cor, var, cov, mean, median, quantile,
SuiteSparse 稀疏数据结构
Test 测试工具
Unicode Unicode 工具
UUIDs 产生 UUID