Search code examples
bashcondaxterm

Activate conda environment within a new xterm terminal


If I run

xterm -hold

and within the new terminal I type

conda activate my_environment

the conda environment "my_environment" is indeed activated.

However, when passing this command using the -e flag, it does not work:

xterm -hold -e "conda activate my_environment"

It instead returns the following error message:

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

So, how can this be done using xterm? Or should I use another type of external terminal?


Solution

  • Background

    The conda activate command is a shell function that gets defined during initialization of the shell. conda init adds code to the initialization file (e.g., .bash_profile) to run the scripts that define the conda activate shell function.

    Solutions

    Possible fix: xterm options

    When using the -c argument with xterm it no longer runs the initialization script. Hence, conda activate never gets defined. For bash there is the -l that tells it to run the init files. I expected xterm's -ls argument to trigger similar behavior, but it didn't work for me. Perhaps someone more familiar can point you to the correct flag.

    Manually Run Conda Script

    Otherwise, you just run the Conda script yourself (assuming it's the bash version). Either of these will work:

    xterm -hold -e ". /path/to/miniconda3/etc/profile.d/conda.sh && conda activate my_environment && which python"
    

    or

    xterm -hold -e "$(conda shell.bash hook) && conda activate my_environment && which python"
    

    The which python is only included to show that you're getting the env activated.

    Conda Run

    Another option is conda run, which automates executing commands under an environment. The follow is equivalent to what I did in the last section, but without having to know what shell I am running in:

    xterm -hold -e "conda run -n my_environment which python"
    

    Just be aware that this functionality is still a work-in-progress. Personally, I've found it quite useful for running simple scripts in specific envs and haven't run into problems.