简体   繁体   中英

How can I define a Nix environment that defaults to Python 3.5

I have defined a the following environment in default.nix :

with import <nixpkgs> {};
stdenv.mkDerivation rec {
  name = "env";
  env = buildEnv { name = name; paths = buildInputs; };
  buildInputs = [
    python35
    python35Packages.pyyaml
  ];
}

If I run nix-shell , python will still be the system python at /usr/bin/python (running on Ubuntu) while python3 is a symlink to the Python 3.5 binary installed by Nix. Is there a way to define the environment so that python is pointing to the Nix Python 3.5?

You can use runCommand to create a new derivation that contains only a python symlink.

with import <nixpkgs> {};
stdenv.mkDerivation rec {
  name = "env";
  env = buildEnv { name = name; paths = buildInputs; };
  buildInputs = [
    (runCommand "python-alias" {} ''
      mkdir -p $out/bin
      ln -s ${python35}/bin/python3 $out/bin/python
    '')
    python35
    python35Packages.pyyaml
  ];
}


nix-shell --pure --run 'python --version'
Python 3.5.3

One simple solution could be to add a shell hook to your environment, to define an alias from python to python3 . This alias will be active only when you run nix-shell :

with import <nixpkgs> {};
stdenv.mkDerivation rec {
  name = "env";
  env = buildEnv { name = name; paths = buildInputs; };
  buildInputs = [
    python35
    python35Packages.pyyaml
  ];
  # Customizable development shell setup
  shellHook = ''
    alias python='python3'
  '';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM