Requirements: Blender 2.80+ (2.79 should also work with pip method, not tested thoroughly)
In order not to mix the packages installed for Blender (such as
scipy
, matplotlib
) with those system-wide packages, we need to
create a virtual environment for the Blender alone.
Best practice is to use a single virtualenv for each version of Blender. See the following steps:
- Find the python binary bundled with Blender, for example
(
/Applications/Blender/blender.app/Contents/Resources/2.79/python/bin/python3.5m
, for version 2.79 on macOS) - Create a virtual environment under the desired location, like:
# Need the following if Blender < 2.80 /path/to/blender/bin/python -m ensurepip # Replace the path according to your system /path/to/blender/bin/python -m pip /path/to/virtualenv
- Activate the virtual environment and install 3rd packages using
pip
# Replace the path and package name according to your system # For Windows system the path is under \path\to\virtualenv\Scripts\activate source /path/to/virtualenv/bin/activate python -m pip install 3rd-party-packages
The packages installed under the virtual environment needs to be found
by the Blender-bundled python, which is done by modifying the
PYTHONPATH
environment variable.
Add the following line at the end of the activate script
(/path/to/virtualenv/bin/activate
):
export PYTHONPATH=$VIRTUAL_ENV/lib/pythonX.Y/site-packages/
Note the actual path may be different if you are using Windows. See comments below.
Reactivate the python vitrualenv will make the Blender-bundled python
detect the 3rd-party package. Test this with a short script (for
example named as test.py
and the package is ase
):
import sys
import bpy
print("Path to search python libraries", sys.path)
print("Python path is: ", bpy.__path__)
try:
import ase
print("ASE library in ", ase.__path__)
except ImportError:
print("ASE not installed!")
Test this script with:
/path/to/blender -b -p test.py
A couple of notes for others using this method:
I'm using blender 2.81 prerelease (bundles python 3.7.4) on Windows 10, and had to do this to create a working virtualenv:
Also, I'm on Windows, so my
activate
is in$VIRTUAL_ENV/Scripts/activate
And one more thing: I had to set PYTHONPATH to
export PYTHONPATH=$VIRTUAL_ENV/Lib/site-packages
.But once I have that straightened out and activate the virtualenv, I can do
pip install
andblender -b --python foo.py
and it finds my modules. Now if onlypython foo.py
would work in the virtualenv! But this is workable.