Nix Recipe: Setup Python

1-minute read

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

  • Create shell.nix with following:

    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).
  • Run nix-shell --pure shell.nix to build and start using python-3.7 in your virtual environment.