如何在Python脚本中激活Conda环境?

时间:2020-11-10 15:11:54

标签: python conda environment

我有一个使用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'.

事实是,我的外壳配置正确。如果我在外壳程序中运行相同的cmd,那么一切都会按预期进行。

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

是否可以从python脚本中运行conda activate base

1 个答案:

答案 0 :(得分:1)

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

尝试以下方法:

conda run -n <environment> <script_name>