How to Import Python Packages in Julia?
Julia is a high-level, high-performance, dynamic programming language for numerical computing. Users can import arbitrary Python modules and libraries into Julia. PyCall package is provided for calling Python from Julia code. You can use PyCall from any Julia code, including within Julia modules. And add this package to the Julia environment with Pkg.add (“PyCall”).
PyCall provides many routines for manipulating Python objects in Julia via a type PyObject. In most cases, PyCall automatically makes the appropriate type conversions to Julia types based on runtime inspection of the Python objects.
To Import Python Packages in Julia. Follow the steps below:
Step 1: using Pkg
Step 2: Pkg.add(“PyCall”)
Step 3: using PyCall
Step 4: @pyimport python_library_name
or
Step 4: pyimport(“python_library_name”)
Example 1:
Julia
using Pkg
Pkg.add( "PyCall" )
using PyCall
@pyimport math
print (math.sin( 90 ))
|
Output:
Example 1
Example 2:
Julia
using Pkg
Pkg.add( "PyCall" )
using PyCall
@pyimport numpy
array1 = numpy.array([ 1 , 2 , 3 , 4 ,
5 , 6 , 7 , 8 , 9 ])
print (array1)
print ( '\n' )
print (numpy.mean(array1))
|
Output:
Example 2
Calling local packages in Julia using PyCall:
Use the following to run packages that are not standard (and are local to your Python IDLE) or using a different environment instead of the standard python env that Julia chooses when @pyimport is invoked. After executing the following two lines, stop and restart the Julia REPL. Note that the location provided corresponds to the directory where your python.exe is located. In my case it was C:\\Users\\hi\\AppData\\Local\\Programs\\Python\\Python37.
Julia
ENV[ "PYTHON" ] = "C:\\Users\\hi\\AppData\\Local\\Programs\\Python\\Python37"
Pkg.build( "PyCall" )
|
Once you have restarted Julia, you can use the usual pyimport to call the respective package local to your installation. Let’s look at an example where I have a package named “cantera” for thermochemical calculations installed in my local environment. I would then use:
Julia
@pyimport cantera as ct
ct.Solution( "gri30.xml" )
|
Last Updated :
10 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...