如何使用 Python 的 juliacall 在 Python 中加载自定义 Julia 包

Prz*_*fel 11 python julia

我已经知道如何将 Julia 包导入到 Python 中

但是,现在我使用以下命令创建了自己的简单 Julia 包: using Pkg;Pkg.generate("MyPack");Pkg.activate("MyPack");Pkg.add("StatsBase") 其中文件MyPack/src/MyPack.jl具有以下内容:

module MyPack
using StatsBase

function f1(x, y)
   return 3x + y
end
g(x) = StatsBase.std(x)

export f1

end
Run Code Online (Sandbox Code Playgroud)

现在我想通过juliacall调用f1g函数在 Python 中加载这个 Julia 包。我已经pip3 install juliacall从命令行运行了。如何从 Python 调用上述函数?

Prz*_*fel 9

您需要运行以下代码来MyPack从 Python 加载包juliacall

from juliacall import Main as jl
from juliacall import Pkg as jlPkg

jlPkg.activate("MyPack")  # relative path to the folder where `MyPack/Project.toml` should be used here 

jl.seval("using MyPack")
Run Code Online (Sandbox Code Playgroud)

现在您可以使用该函数(请注意,调用非导出函数需要包名称):

>>> jl.f1(4,7)
19

>>> jl.f1([4,5,6],[7,8,9]).to_numpy()
array([19, 23, 27], dtype=object)

>>> jl.MyPack.g(numpy.arange(0,3))
1.0
Run Code Online (Sandbox Code Playgroud)

请注意,从 Python 调用 Julia 的另一个选项似乎更难配置,即此处pip install julia描述的包:我有一个用 Julia 编写的高性能函数,如何从 Python 使用它?