Python packages in nix containers

I am currently trying to build a nix container setup with python and some packages.
I think I am missing something regarding python packages.

My container configuration looks like this:

{ config, lib, pkgs, ... }:
with lib;
{
  boot.isContainer = true;
  networking.hostName = mkDefault "blacknix";
  networking.useDHCP = false;

  users = {
    users = {
      blacknix = {
        isNormalUser = true;
        uid = 1000;
        description = "BlackNix User";
        password = "blacknix";
        extraGroups = [ "wheel" ];
      };
    };
  };
  environment.systemPackages = with pkgs; [
    python3
    python3Packages.numpy
  ];
}

However, when I login, python does not seem to find the module.

[blacknix@blacknix:~]$ python
Python 3.8.11 (default, Jun 28 2021, 10:57:31)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'numpy'
>>>

Can someone tell me what Iā€™m missing here?

Thanks

It looks like, that the installed packages do not get added to the sys.path:

Python 3.8.11 (default, Jun 28 2021, 10:57:31)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> for path in sys.path:
...     print(path)
...

/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python38.zip
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8/lib-dynload
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8/site-packages
>>>

For comparison, the same package using nix-shell:

nix-shell -p python38Packages.numpy

[nix-shell:~]$ python
Python 3.8.11 (default, Jun 28 2021, 10:57:31)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> for path in sys.path:
...     print(path)
...

/nix/store/gf8pgv18zvv4jv4jmgblvfksiry67na0-python3.8-numpy-1.20.2/lib/python3.8/site-packages
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8/site-packages
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python38.zip
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8
/nix/store/32q6ryrb860sksdi1al5djg3pgcpq92l-python3-3.8.11/lib/python3.8/lib-dynload

Update: It works now when I do it this way:

environment.systemPackages = with pkgs; [
        (python38.withPackages(ps: with ps; [
          numpy
        ]))
];
1 Like