在 python 中运行 Julia .jl 文件

2022-01-23 00:00:00 python julia

问题描述

我正在尝试在 Python 中运行 Julia .jl 文件,但是在尝试了不同的选项之后,它们都不起作用.

I'm trying to run a Julia .jl file in Python, however, after having tried different options none of them is working.

我尝试过使用 PyJulia.导入 Julia 并定义一个 Julia 对象.没有达到.

I've tried to use PyJulia. Import Julia and define a Julia object. Not achieved.

有没有人混合使用 Python 和 Julia 技术并取得了成功?(从 Python 运行 Julia)

Has anyone mix Python and Julia technologies and has succeeded? (run Julia from Python)


解决方案

首先在 Julia REPL 中运行 Pkg.add("PyCall") 在 Julia 中安装 PyCall 包.

First install PyCall package in Julia by running Pkg.add("PyCall") in Julia REPL.

接下来你需要为 Python 安装 julia:

Next you need to install julia for Python:

$ pip install julia

应该可以.这是我的控制台的输出(您应该会看到类似的内容):

should work. Here is the output from my console (you should see something similar):

$ pip install julia
Collecting julia
  Downloading julia-0.1.5-py2.py3-none-any.whl (222kB)
    100% |████████████████████████████████| 225kB 1.1MB/s
Installing collected packages: julia
Successfully installed julia-0.1.5

现在假设您的工作目录中有以下文件 test.jl:

Now assume you have the following file test.jl in your working directory:

for i in 1:10
    println(i)
end
1+2

(它应该打印从 1 到 10 的数字,并返回值 3,它是 1 和 2 之和的结果).

(it should print numbers from 1 to 10, and return value 3 which is the result of sum of 1 and 2).

现在你启动 Python REPL 并使用 julia 包如下运行自定义 Julia 脚本:

Now you start Python REPL and use julia package as follows to run a custom Julia script:

>>> import julia
>>> j = julia.Julia()
>>> x = j.include("test.jl")
1
2
3
4
5
6
7
8
9
10
>>> x
3

如您所见,您已将 Julia 脚本的返回值分配给 Python 中的变量 x.

And as you can see you have the return value of Julia script assigned to variable x in Python.

您可以在此处找到更多详细信息:https://github.com/JuliaPy/pyjulia.

You can find more details here: https://github.com/JuliaPy/pyjulia.

相关文章