Search code examples
pythoncondaenvironment

How to activate a Conda environment within a Python script?


I have a script using os.system(cmd) to run a pipe. I need the pipe to run in a specific Conda environment, so I tried to do something like this:

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

However, I get:

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'.

The fact is, my shell is properly configured. If I run the same cmd in the shell, everything works as expected.

I have tried using subprocess.run(cmd, shell=True) as well, but I get the same result.

Is there a way to run conda activate base from within a python script?


Solution

  • conda activate is really intended to be used in interactive settings (shells/command prompts). But you can use conda run to execute a particular python script within a given environment.

    Try this instead:

    conda run -n <environment> <script_name>