Running a Python project from GitHub on NixOS without the project being packaged in nixpkgs can indeed be streamlined using a few different approaches. Here's a more efficient way to handle this, leveraging Nix features and tools:
1. Use nix-shell with shell.nix
While you've mentioned this approach, it's worth noting that nix-shell can be very effective if you set it up correctly. You can pin dependencies and ensure that your environment is consistent. Below is a basic template:
nix
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
buildInputs = [
pkgs.python39 # Or whichever Python version you prefer
pkgs.python39Packages.requests # Example Python package
# Add other C libraries or dependencies as required
];
# For Python dependencies not available in nixpkgs, you can use pip with Nix
shellHook = ''
echo "Setting up custom environment..."
PIP_PREFIX=`mktemp -d`
export PATH="$PIP_PREFIX/bin:$PATH"
export PYTHONPATH="$PIP_PREFIX/lib/python3.9/site-packages"
pip install --prefix=$PIP_PREFIX -r requirements.txt
'';
}
This shell.nix file creates a clean environment with specified packages and uses pip to handle Python dependencies not available in nixpkgs.
2. Use poetry2nix
If your project utilizes poetry, you can use the poetry2nix tool, which helps in creating reproducible builds of Python projects:
Place this in your shell.nix, ensuring your project has a poetry.lock file in the root directory.
3. Use mach-nix
mach-nix is another tool for managing Python environments on Nix. It is especially useful for handling complex dependencies found on PyPI:
nix
{ pkgs ? import <nixpkgs> {} }:
let
mach-nix = import (fetchTarball "https://github.com/DavHau/mach-nix/tarball/3.3.0");
in
mach-nix.mkPython {
requirements = ''
# list your Python requirements here
requests
flask
# or point to a requirements.txt file
'';
# optional - specify the CPython version
python = "python39";
}
4. Use direnv with Nix integration
By integrating direnv with nix-shell, you can automatically load the Nix environment when you navigate to your project directory:
Install direnv.
Create a .envrc file containing:
bash
use nix
Allow the .envrc file by running:
bash
direnv allow
This method is particularly user-friendly and ensures your environment is set up seamlessly as you develop.
Conclusion
Each of these methods has its pros and cons, and the right choice depends on your workflow preferences and project requirements. For more complex or professional setups, packaging your project and contributing to nixpkgs might also be worth considering if you plan to frequently deploy or distribute this project on NixOS systems.