I have a found a Julia function that nicely does the job I need.
How can I quickly integrate it to be able to call it from Python?
Suppose the function is
f(x,y) = 2x.+y
What is the best and most elegent way to use it from Python?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Assuming your Python and Julia are installed you need to take the following steps.
-
Run Julia and install
PyCallusing Pkg pkg"add PyCall"
-
Put your code into a Julia package
using Pkg Pkg.generate("MyPackage")In the folder
srcyou will findMyPackage.jl, edit it to look like this:module MyPackage f(x,y) = 2x.+y export f end
-
Install pyjulia
python -m pip install julia
(On Linux systems you might want to use
python3instead ofpythoncommand)For this step note that while an external Python can be used with Julia. However, for a convenience it might be worth
to consider using a Python that got installed together with Julia asPyCall.
In that case for installation use a command such this one:%HOMEPATH%.juliaconda3python -m pip install julia
or on Linux
~/.julia/conda/3/python -m pip install julia
Note that if you have
JULIA_DEPOT_PATHvariable defined you can replace%HOMEPATH%.juliaor~/.julia/with its value. -
Run the appropiate Python and tell it to configure the Python-Julia integration:
import julia julia.install() -
Now you are ready to call your Julia code:
>>> from julia import Pkg >>> Pkg.activate(".\MyPackage") #use the correct path Activating environment at `MyPackageProject.toml` >>> from julia import MyPackage >>> MyPackage.f([1,2],5) [7,9]
It is worth noting that the proposed approach in this answer has several advantages over a standalone Julia file which would be possible, although is less recommended. The advantages include:
- Packages get precompiled (so they are faster in subsequent runs) and can be loaded as a package in Python.
- Packages come with their own virtual environment via 1Project.toml` which makes production deployments much comfortable.
- A Julia package can be statically compiled into Julia’s system image which can slash itsloading time — see https://github.com/JuliaLang/PackageCompiler.jl .
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0