3

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?

alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • 1
    If this is macOS/linux, you need to `source /etc/profile.d/conda.sh` before you can run conda commands. – cel Nov 10 '20 at 15:16
  • @cel It worked. Can you post it as an answer? – alec_djinn Nov 10 '20 at 15:43
  • my anaconda installation is perfectly valid yet conda.sh in that particular path is not set with executable permissions. Hence use `. /etc/profile.d/conda.sh` to force its execution. – matanster Dec 03 '21 at 16:29
  • Does this answer your question? [Using subprocess in anaconda environment](https://stackoverflow.com/questions/51819719/using-subprocess-in-anaconda-environment) – Sander Vanden Hautte Apr 05 '23 at 10:20

1 Answers1

3

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>