【问题标题】:How to activate a Conda environment within a Python script?如何在 Python 脚本中激活 Conda 环境?
【发布时间】:2020-11-10 15:11:54
【问题描述】:

我有一个使用os.system(cmd) 运行管道的脚本。我需要管道在特定的 Conda 环境中运行,所以我尝试做这样的事情:

cmd = 'conda activate base && ' + cmd
os.system(cmd)

但是,我得到:

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

事实上,我的 shell 配置正确。如果我在 shell 中运行相同的 cmd,一切都会按预期运行。

我也尝试过使用subprocess.run(cmd, shell=True),但得到了相同的结果。

有没有办法在 python 脚本中运行conda activate base

【问题讨论】:

  • 如果是macOS/linux,需要source &lt;conda-base&gt;/etc/profile.d/conda.sh才能运行conda命令。
  • @cel 成功了。您可以将其发布为答案吗?
  • 我的 anaconda 安装完全有效,但该特定路径中的 conda.sh 未设置可执行权限。因此使用. &lt;conda-base&gt;/etc/profile.d/conda.sh 强制执行。

标签: python conda environment


【解决方案1】:

conda activate 真正旨在用于交互式设置(shell/命令提示符)。但是您可以使用conda run 在给定环境中执行特定的python 脚本。

试试这个:

conda run -n <environment> <script_name>

【讨论】:

  • 我收到permission denied
  • 我无法重现该错误,但听起来好像您已经有了@cel 发布的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2016-07-16
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多