Featured image of post Nix Recipe: Setup Python

Nix Recipe: Setup Python

Nix recipe to setup python in a cross platform virtual nix environment

This is a nix recipe for building and running python in a virtual nix environment.

Step 1: Create shell.nix

Create shell.nix with following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
let
nixpkgs = import (builtins.fetchTarball https://github.com/NixOS/nixpkgs/archive/20.03.tar.gz) {
  overlays = [];
  config = {};
};

in
with nixpkgs;

stdenv.mkDerivation {
  name = "python-env";

  nativeBuildInputs = [
    zsh
    vim
    python37
    python37Packages.pip
    python37Packages.virtualenv
  ];

  # ENV variables
  PROJDIR = "${toString ./.}";

  # Post Shell Hook
  shellHook = ''
    echo "Using ${python37.name}"

    [ ! -d '$PROJDIR/python-dev' ] && virtualenv python-dev && echo "SETUP python-dev: DONE"
    source python-dev/bin/activate
    # python -m pip install -r requirements.txt
  '';
}

Note:

  • Here, the nix packages are installed from 20.03 release.
  • virtualenv is installed and activated, and python requirements are installed in this environment (via requirements.txt file).

Step 2: Run nix shell

Now run below command to build and start using python-3.7 in your virtual environment.

1
nix-shell --pure shell.nix