Integrating with external Python libraries¶

(Back to Overview)

The PyCall.jl package lets you call external python libraries

In [6]:
using PyCall

Importing Modules¶

You use the pyimport function to import a python module

In [7]:
math = pyimport("math")
Out[7]:
PyObject <module 'math' from '/Users/blaschke/.julia/conda/3/lib/python3.8/lib-dynload/math.cpython-38-darwin.so'>

Imported modules now look like Julia modules

In [8]:
math.sin(math.pi / 4)
Out[8]:
0.7071067811865475

Managing Dependencies¶

You can manage the python executable, and therefore the python search path using the PYTHON environment variable. Right now, I don't have anything set, so it defaults to Julia's own conda environment:

In [15]:
PyCall.libpython
Out[15]:
"/Users/blaschke/.julia/conda/3/lib/libpython3.8.dylib"

Let's add scipy to this conda install (from Julia):

In [12]:
using Conda
In [13]:
Conda.add("scipy")
┌ Info: Running `conda install -y scipy` in root environment
└ @ Conda /Users/blaschke/.julia/packages/Conda/x2UxR/src/Conda.jl:127
Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... done

## Package Plan ##

  environment location: /Users/blaschke/.julia/conda/3

  added / updated specs:
    - scipy


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    libcxx-14.0.6              |       hccf4f1f_0         1.3 MB  conda-forge
    scipy-1.8.1                |   py38hb261484_2        21.9 MB  conda-forge
    ------------------------------------------------------------
                                           Total:        23.3 MB

The following NEW packages will be INSTALLED:

  scipy              conda-forge/osx-64::scipy-1.8.1-py38hb261484_2

The following packages will be UPDATED:

  libcxx                         pkgs/main::libcxx-10.0.0-1 --> conda-forge::libcxx-14.0.6-hccf4f1f_0



Downloading and Extracting Packages
libcxx-14.0.6        | 1.3 MB    | #################################### | 100% 
scipy-1.8.1          | 21.9 MB   | #################################### | 100% 
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
Retrieving notices: ...working... done

Now we can use scipy from Julia:

In [14]:
so = pyimport("scipy.optimize")
so.newton(x -> cos(x) - x, 1)
Out[14]:
0.7390851332151607