Skip to content

Instantly share code, notes, and snippets.

@adisbladis
Created April 10, 2019 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adisbladis/6a152e6108f57a5071a441fcecb00395 to your computer and use it in GitHub Desktop.
Save adisbladis/6a152e6108f57a5071a441fcecb00395 to your computer and use it in GitHub Desktop.
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()
try:
nix.eval("""
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)
realise_path(store_path)
paths = os.environ['PATH'].split(':')
if store_path not in paths:
paths.insert(0, store_path)
os.environ['PATH'] = ':'.join(paths)
if __name__ == '__main__':
add_path('openssl')
subprocess.run(['openssl'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment