Python: Difference between revisions

Using nix-ld: Explain how to use python with a venv
DHCP (talk | contribs)
m Using nix-ld: use <syntaxhighlight lang=console> for shell commands
 
(One intermediate revision by one other user not shown)
Line 228: Line 228:
   ];
   ];
}
}
</syntaxhighlight>Then, you can use your own pythonld in a specific virtual env like:<syntaxhighlight lang="bash">
</syntaxhighlight>Then, you can use your own pythonld in a specific virtual env like:<syntaxhighlight lang="console">
$ pythonld -m venv myvenv
$ pythonld -m venv myvenv
$ source myvenv/bin/activate
$ pip install …
$ python
… this python has dependencies installed via pip installed …
</syntaxhighlight>If you want to also install system-wide nix dependencies like numpy so that you don't need to reinstall them in every venv, you can also install them system-wide via:<syntaxhighlight lang="nix">
{
  programs.nix-ld = {
    enable = true;
    libraries = with pkgs; [
      zlib zstd stdenv.cc.cc curl openssl attr libssh bzip2 libxml2 acl libsodium util-linux xz systemd
    ];
  };
  # Usage: to create a venv, just do:
  # $ pythonld -m venv --system-site-packages myvenv
  # $ source myvenv/bin/activate
  # $ pip install …
  # https://github.com/nix-community/nix-ld?tab=readme-ov-file#my-pythonnodejsrubyinterpreter-libraries-do-not-find-the-libraries-configured-by-nix-ld
  # Important: don't forget the -a "$0" or venv will skip your wrapper.
  environment.systemPackages = [
    (pkgs.writeShellScriptBin "pythonld" ''
      export LD_LIBRARY_PATH=$NIX_LD_LIBRARY_PATH
      exec -a "$0" ${(pkgs.python3.withPackages (ps: with ps; [ numpy ]))}/bin/python "$@"
    '')
  ];
}
</syntaxhighlight>And then use it like:<syntaxhighlight lang="console">
$ pythonld -m venv --system-site-packages myvenv
$ source myvenv/bin/activate
$ source myvenv/bin/activate
$ pip install …
$ pip install …