-
-
Save 573/0d09229c3b46a969fe52cae68a1d0272 to your computer and use it in GitHub Desktop.
build nix shell from python requirements.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# build python nix shell from a local `./requirements.txt` | |
mkdir ./env | |
cat > ./env/flake.nix << 'EOF' | |
{ | |
inputs = { | |
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; | |
flake-utils.url = "github:numtide/flake-utils"; | |
poetry2nix = { | |
url = "github:nix-community/poetry2nix"; | |
inputs.nixpkgs.follows = "nixpkgs"; | |
inputs.flake-utils.follows = "flake-utils"; | |
}; | |
}; | |
outputs = { self, nixpkgs, flake-utils, poetry2nix }: | |
flake-utils.lib.eachDefaultSystem (system: | |
let | |
myapp = { poetry2nix, lib }: poetry2nix.mkPoetryApplication { | |
projectDir = self; | |
overrides = poetry2nix.overrides.withDefaults (self: super: | |
lib.mapAttrs | |
(attr: systems: super.${attr}.overridePythonAttrs | |
(old: { | |
nativeBuildInputs = (old.nativeBuildInputs or [ ]) ++ map (a: self.${a}) systems; | |
})) | |
{ | |
# override build systems when necessary | |
# https://github.com/nix-community/poetry2nix/blob/master/docs/edgecases.md#modulenotfounderror-no-module-named-packagename | |
# package = [ "setuptools" ]; | |
} | |
); | |
}; | |
pkgs = import nixpkgs { | |
inherit system; | |
overlays = [ | |
poetry2nix.overlays.default | |
(final: _: { | |
myapp = final.callPackage myapp { }; | |
}) | |
]; | |
}; | |
in | |
{ | |
packages.default = pkgs.myapp; | |
devShells = { | |
default = pkgs.mkShell { | |
inputsFrom = [ pkgs.myapp ]; | |
}; | |
poetry = pkgs.mkShell { | |
packages = [ pkgs.poetry ]; | |
}; | |
}; | |
} | |
); | |
} | |
EOF | |
# init a dummy poetry project | |
nix develop ./env#poetry -c poetry init --name env -n -C env | |
# convert requirements.txt to dependencies in pyproject using poetry | |
# see: https://stackoverflow.com/questions/62764148/how-to-import-an-existing-requirements-txt-into-a-poetry-project | |
nix develop ./env#poetry -c poetry add $(cat requirements.txt) --lock -C env | |
# you might need to edit the `flake.nix` to override python build systems for some packages, or add some native dependencies, | |
# otherwise: | |
echo 'run "nix develop ./env -c python" to start the python with environment' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment