Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
alec_djinn Avatar asked May 25 '26 01:05

alec_djinn


1 Answers

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>
like image 78
downlandpale Avatar answered May 27 '26 14:05

downlandpale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!