How to import Julia packages into Python
Asked Answered
D

1

6

One can use Julia's built-in modules and functions using the juliacall package. for example:

>>> from juliacall import Main as jl
>>> import numpy as np

# Create a 2*2 random matrix
>>> arr = jl.rand(2,2)

>>> arr
<jl [0.28133223988783074 0.22498491616860727; 0.008312971104033062 0.12927167014532326]>

# Check whether Numpy can recognize the shape of the array or not
>>> np.array(arr).shape
(2, 2)

>>> type(np.array(arr))
<class 'numpy.ndarray'>

Then I'm curious to know if importing an installed julia package into Python is possible? For example, let's say that one wants to import Flux.jl into Python. Is there a way to achieve this?

Distrain answered 21/7, 2022 at 18:5 Comment(0)
D
5

I found it by scrutinizing the pictures of the second example of the juliacall GitHub page. According to the example, I'm able to import Flux.jl by taking these steps:

>>> from juliacall import Main as jl
>>> jl.seval("using Flux")

Also, one can install any registered Julia package using Pkg in Python:

>>> from juliacall import Main as jl
>>> jl.Pkg.add("Flux")

# After a successful installation

>>> jl.Pkg.status()
Status `C:\Users\Shayan\miniconda3\envs\im\julia_env\Project.toml`
  [587475ba] Flux v0.14.10
  [6099a3de] PythonCall v0.9.15

# This indicates that the installation was successful

Additional note

One can use Julia packages in Python using the pyjulia package that can be installed using pip install julia in Python. Afterward, the following commands should be entered:

>>> import julia
>>> julia.install()

# Then

>>> from julia import Pkg
>>> Pkg.add("Flux")

# After a successful installation
>>> Pkg.status()
Status `C:\Users\Shayan\.julia\environments\v1.10\Project.toml`
  [587475ba] Flux v0.14.10

# This indicates that the installation was successful

>>> from julia import Flux

You can also say, from julia import Flux as flx. Note that using juliacall is recommended.

Distrain answered 21/7, 2022 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.