Skip to content

Instantly share code, notes, and snippets.

@araa47
Last active February 8, 2024 10:51
Show Gist options
  • Save araa47/10537f74ee061b26e18ae21d4bfca7d9 to your computer and use it in GitHub Desktop.
Save araa47/10537f74ee061b26e18ae21d4bfca7d9 to your computer and use it in GitHub Desktop.
Python3 Dev Environment with Pipenv using Nix and direnv for Linux and macOS

System Set-Up

  1. Install nix on your system curl https://nixos.org/nix/install | sh
  2. . ~/.nix-profile/etc/profile.d/nix.sh
  3. Install direnv nix-env -i direnv
  4. Add hook into shell by running eval "$(direnv hook bash)" , you will need to add this to .bash_profile to make it presistant

Project Set-Up

Create a shell.nix file in your project with the following content. This has python 3.7 and pipenv as buildInputs

with import <nixpkgs> {};
stdenv.mkDerivation {
  name = "my-python-project";
  buildInputs = [ python37 pipenv ];
}

Create a .envrc file with the following content.

use nix
layout_pipenv

Optional PS1

Finally if required add the following to your .bash_profile if you want it to display the pipenv it has activated when you cd into the project.

show_virtual_env() {
  if [[ -n "$VIRTUAL_ENV" && -n "$DIRENV_DIR" ]]; then
    echo "($(basename $VIRTUAL_ENV))"
  fi
}
export -f show_virtual_env
PS1='$(show_virtual_env)'$PS1

@mattiasflodin
Copy link

mattiasflodin commented Feb 8, 2024

What is a layout and why do I need it?

It seems that with layout_pipenv, direnv removes pipenv from the path so I can't create a new environment. Entering the direnv environment makes pipenv output

direnv: No Pipfile found.  Use `pipenv` to create a `Pipfile` first.

but since pipenv is not on the path, I can't follow those instructions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment