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