Conda 仅为 env 设置 LD_LIBRARY_PATH

2022-01-10 00:00:00 python conda virtualenv anaconda

问题描述

我安装了 miniconda3,在其中创建了一个名为 py35 的虚拟环境.我有一些我只想在这个环境中使用的库.因此他们在

/.../miniconda3/envs/py35/libs

但是在环境中找不到它们,因为 LD_LIBRARY_PATH 不包含所述文件夹.我现在想将 LD_LIBRARY_PATH 设置为仅当我在虚拟环境中时才包含/lib.

我正在考虑修改 miniconda 用于启动环境的激活脚本,但不太确定这是标准做法还是有更简单的方法来实现这一点.

解决方案

您可以通过编辑 activate.d/env_vars.sh 脚本在激活环境时设置环境变量.见这里:https://conda.io/docs/user-guide/tasks/manage-environments.html#macos-and-linux

该链接的关键部分是:

<块引用>

  1. 在终端中找到 conda 环境的目录窗口,例如 /home/jsmith/anaconda3/envs/analytics.

  2. 进入该目录并创建这些子目录和文件:

    cd/home/jsmith/anaconda3/envs/analyticsmkdir -p ./etc/conda/activate.dmkdir -p ./etc/conda/deactivate.d触摸 ./etc/conda/activate.d/env_vars.sh触摸 ./etc/conda/deactivate.d/env_vars.sh

  3. 编辑./etc/conda/activate.d/env_vars.sh如下:

    #!/bin/sh导出 MY_KEY='秘密键值'导出 MY_FILE=/path/to/my/file/

  4. 编辑./etc/conda/deactivate.d/env_vars.sh如下::

    #!/bin/sh取消设置 MY_KEY取消设置 MY_FILE

当您运行 conda activate analytics 时,环境变量 MY_KEY 和 MY_FILE 设置为您写入的值文件.当你运行 conda deactivate 时,这些变量是删除.

I have an installation of miniconda3 where I have created a virtual environment called py35. I have some libraries that I only want to use from within this environment. hence they are under

 /.../miniconda3/envs/py35/libs

However they are not found from within the environment as LD_LIBRARY_PATH does not contain said folder. I now want to set LD_LIBRARY_PATH to include the /lib only when I am in the virtual environment.

I was thinking of modifying the activate script miniconda uses to start the environment but am not quite sure if this is standard practice or if there is an easier way to achieve this.

解决方案

You can set environment variables when an environment is activated by editing the activate.d/env_vars.sh script. See here: https://conda.io/docs/user-guide/tasks/manage-environments.html#macos-and-linux

The key portions from that link are:

  1. Locate the directory for the conda environment in your Terminal window, such as /home/jsmith/anaconda3/envs/analytics.

  2. Enter that directory and create these subdirectories and files:

    cd /home/jsmith/anaconda3/envs/analytics
    mkdir -p ./etc/conda/activate.d
    mkdir -p ./etc/conda/deactivate.d
    touch ./etc/conda/activate.d/env_vars.sh
    touch ./etc/conda/deactivate.d/env_vars.sh
    

  3. Edit ./etc/conda/activate.d/env_vars.sh as follows:

    #!/bin/sh
    
    export MY_KEY='secret-key-value'
    export MY_FILE=/path/to/my/file/
    

  4. Edit ./etc/conda/deactivate.d/env_vars.sh as follows::

    #!/bin/sh
    
    unset MY_KEY
    unset MY_FILE
    

When you run conda activate analytics, the environment variables MY_KEY and MY_FILE are set to the values you wrote into the file. When you run conda deactivate, those variables are erased.

相关文章