Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add derivations to PATH at runtime from python
#!/usr/bin/env python
# Add binaries to PATH at runtime
import subprocess
import nix
import os
def realise_path(store_path: str):
if not os.path.exists(store_path):
# Abuse IFD to realise store path
# Try to import a file that will never exist
dummy_file = hashlib.sha1(store_path.encode()).hexdigest()
import "${%s}/%s.nix"
""" % (store_path, dummy_file))
except nix.NixError as ex:
# This is expected.
# What really matters now is whether the store path exists.
# If it does, the realization was a success.
# Otherwise, it's likely a missing/misspelt derivation name
if not os.path.exists(store_paths[0]):
raise ex
def add_path(drv_name: str):
store_path = nix.eval("""
with import <nixpkgs> {};
"${lib.getBin %s}/bin"
""" % drv_name)
paths = os.environ['PATH'].split(':')
if store_path not in paths:
paths.insert(0, store_path)
os.environ['PATH'] = ':'.join(paths)
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.