Install python packages for Blender interpreter

I am trying to write a python script that uses blender, which forces me to use Blender’s python interpreter like this:

blender -P run.py

Now I would like to install scipy for this python interpreter, which would normally be done with pip:

path/to/blender/bin/python -m pip install scipy

, but pip is generally not allowed to install packages in nixos. How would I install python packages for the blender interpreter using a nix configuration file?

I am using home-manager without flakes

If you need a quick fix, you can use a virtual env:

path/to/blender/bin/python -m venv .venv 

If you need a declarative approach, you can use the makeWrapper hook:

wrapProgram $out/bin/myprogram \
  --set PYTHONPATH "${
    python313.pkgs.makePythonPath [
      python313Packages.scipy
    ]
  }:$PYTHONPATH" \
  --set PATH "${I don't know where blender puts its interpreter xd}/bin:$PATH"
'';
1 Like

Thank you! Can you please elaborate a bit on that? I don’t even know where to put this, as I am very beginner.

I have a similar problem with qmk. I created a flake.nix in the project directory and set up a shell with the python packages in the flake. It works, but I would like to learn another way and find out what’s better and why.

Thanks!

Thank you for the reply!

I couldn’t figure out the wrapProgram command, so I ended up using a nix-shell that works:

{ pkgs ? import <nixpkgs> {} }:
let
  # Blender uses a fixed python version, 5.0 uses 3.11
  blenderPython = pkgs.python311;

  pythonWithPackages = blenderPython.withPackages (ps: [
    ps.scipy
  ]);
in
pkgs.mkShell {
  packages = [
    pkgs.blender
    pythonWithPackages
  ];

  shellHook = ''
    export PYTHONPATH="${pythonWithPackages}/${pythonWithPackages.sitePackages}:$PYTHONPATH"
  '';
}

I’m not sure if this still works when other python interpreters like 3.13 are also installed

wrapProgram is commonly used for builds, so the shell is good. I leave an example for @schemar:

{
  stdenv,
  makeWrapper,
  python313,
  python313Packages,
}:

stdenv.mkDerivation {
  pname = "yourpkg";
  version = "0.1.0";

  src = ./src;

  nativeBuildInputs = [ makeWrapper ];

  installPhase = ''
    mkdir -p $out/bin

    install -m755 program.py $out/bin/program.py
    wrapProgram $out/bin/program.py \
      --set PYTHONPATH "${
        python313.pkgs.makePythonPath [
          python313Packages.scipy
        ]
      }:$PYTHONPATH" \
      --set PATH "${python313}/bin:$PATH"
  '';
}
1 Like