Skip to content

Instantly share code, notes, and snippets.

@luochen1990
Created February 14, 2022 08:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luochen1990/20f2ed53450b419e720413395328417d to your computer and use it in GitHub Desktop.
Save luochen1990/20f2ed53450b419e720413395328417d to your computer and use it in GitHub Desktop.
(示例) 在 NixOS 中构建可用 pip 的 python 隔离环境
#!/usr/bin/env nix-shell
#! nix-shell shell.nix
{ pkgs ? import <nixpkgs> {} }:
(pkgs.buildFHSUserEnv {
name = "devbox";
targetPkgs = pkgs: (with pkgs; [
python38
python38Packages.pip
python38Packages.virtualenv
openssl
zlib
stdenv.cc.cc.lib
pythonManylinuxPackages.manylinux2014Package
]);
profile = ''
python3 -m venv ${builtins.toString ./.venv-py38}
source ${builtins.toString ./.venv-py38/bin/activate}
pip3 install -e ${builtins.toString ./.}
'';
runScript = "bash";
}).env
@luochen1990
Copy link
Author

使用方法:

wget https://gist.githubusercontent.com/luochen1990/20f2ed53450b419e720413395328417d/raw/757c4b9ca6ef9903f7e058cc4a68d197b65c671e/shell.nix
chmod +x shell.nix
./shell.nix

之后就进入了一个虚拟环境, 该环境满足:

  1. 系统目录结构符合 FHS 约定
  2. python 版本由 nix 脚本所指定
  3. 由 nix 脚本所指定的 python 包已经可用 (类似于已经用 pip 安装, 但 reproducible)
  4. 已经进入 venv, 且 pip 可用 (pip install 将会把包安装到 venv 中)

虽然可以在虚拟的隔离环境里用 pip, 但是还是建议能写进 nix 脚本的依赖就写到 nix 脚本里, 更 reproducible (虽然并没有, 因为没flake锁定版本).

另外即使要用 pip 安装, 也建议写在 profile 脚本里 (如 20行), 至少这样是声明式的, 即使 venv 目录被删了也没关系, 因为依赖信息记录在该脚本里.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment