Linking Python packages to Blender


#1

Blender ships with its own Python environment, which is based on Python version 3.5 for the current 2.79 release and version 3.6 for the 2.80 alpha. This Python environment has its own executable (/blender/2.80/python/bin/python3.6) and local packages folder (/blender/2.80/python/lib/python3.6/).

The easiest way to get access in Blender to other packages such as SciPy, Numba, Matplolib etc, is to add the site-packages folder containing these packages to your PYTHONPATH (making sure this folder’s packages matches the Python version of Blender, 3.5 or 3.6).

For Unix systems, this is done by appending your site-packages folder in your .bashrc / .profile / .bash_profile files,

export PYTHONPATH="/usr/lib/python3.6/site-packages:$PYTHONPATH"

or in Windows using the system’s environment variables.

Once the folder is added to the PYTHONPATH, then checking sys.path in Blender will show Blender’s own default Python paths, and your own compas and other custom paths.

/home/al/blender/2.80/scripts/addons_contrib
/home/al/blender/2.80/scripts/addons
/home/al/blender/2.80/scripts/startup
/home/al/blender/2.80/scripts/modules
/home/al/blender/2.80/python/lib/python3.6
/home/al/blender/2.80/python/lib/python3.6/lib-dynload
/home/al/blender/2.80/python/lib/python3.6/site-packages
/home/al/blender/2.80/scripts/freestyle/modules
/home/al/blender/2.80/scripts/addons/modules
/home/al/.config/blender/2.80/scripts/addons/modules
/usr/lib/python3.6/site-packages
/home/al/compas/src

You can then proceed as normal as you would in your own system CPython manner, with all additional Blender functionality.


#2

An alternative to adding site-packages to the PYTHONPATH is to link Blender to the external Python you want to use.

This is particularly convenient when using conda environments. For example, in order to create a full conda environment and use it on Blender 2.79 on Windows, first create and install packages:

conda create -n blender-353 python=3.5.3
conda activate blender-353
conda install numpy scipy <add more packages as desired...>

Then, link Blender to the newly installed Python interpreter:

cd %PROGRAMFILES%\Blender Foundation\Blender\2.79
move python embedded_python
mklink /j python %CONDA_PREFIX%

(the last line is Windows’ ln command, in *nix it would be something like ln -s $CONDA_PREFIX python)

And that should be it.