激活 conda env 与从 conda env 调用 python 解释器

activating conda env vs calling python interpreter from conda env

这两个操作究竟有什么区别?

source activate python3_env && python my_script.py~/anaconda3/envs/python3_env/bin/python my_script.py ?

似乎激活环境会向$PATH 添加一些变量,但第二种方法似乎可以访问安装在python3_env 中的所有模块。引擎盖下还有其他事情吗?

您是对的,激活环境会向 PATH 环境变量添加一些目录。特别是,这将允许安装在环境中的任何二进制文件或脚本优先 运行,而不是基础环境中的二进制文件或脚本。例如,如果您已将 IPython 安装到您的环境中,激活该环境允许您编写

ipython

在环境中启动IPython,而不是

/path/to/env/bin/ipython

此外,环境可能具有添加或编辑在激活环境时执行的其他环境变量的脚本(请参阅 conda docs)。这些脚本可以对 shell 环境进行任意更改,甚至包括更改 PYTHONPATH 以更改包的加载位置。

最后,我写了一个非常详细的答案,说明那里的代码到底发生了什么: 不过,这可能是也可能不是最新的。答案的相关部分是:

...the build_activate method adds the prefix to the PATH via the _add_prefix_to_path method. Finally, the build_activate method returns a dictionary of commands that need to be run to "activate" the environment.

And another step deeper... The dictionary returned from the build_activate method gets processed into shell commands by the _yield_commands method, which are passed into the _finalize method. The activate method returns the value from running the _finalize method which returns the name of a temp file. The temp file has the commands required to set all of the appropriate environment variables.

Now, stepping back out, in the activate.main function, the return value of the execute method (i.e., the name of the temp file) is printed to stdout. This temp file name gets stored in the Bash variable ask_conda back in the _conda_activate Bash function, and finally, the temp file is executed by the eval Bash function.

所以你可以看到,根据环境的不同,运行宁conda activate python3_env && python my_script.py~/anaconda3/envs/python3_env/bin/python my_script.py可能会给出非常不同的结果。