Conda environments and Terminal

Conda init

This post introduces the following tricks:

  • activate a conda environment
  • shift the environments in conda

After we call conda init, the next time you open an terminal, it will by default be in the (base) python environment. Only in this env you could change the conda env. Use conda activate [env name], and use conda deactivate to exit the env, going back to the (base).

Within the (base), if you deactivate again, and you will exit the conda prompt.

Notice that, once you init the conda, all the terminals by default will be a (base) when opening. To revert the changes, do conda init --reverse.

Behind the scene, the powershell creates a profile in C:\Users\yimin\Documents\WindowsPowerShell

#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
If (Test-Path "C:\Users\yimin\anaconda3\Scripts\conda.exe") {
    (& "C:\Users\yimin\anaconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression
}
#endregion

And every time it prompts, the base environment will be invoked.

Without conda init, conda activate <env_name> will not work in shell, unless you are at Conda Prompt.

Activate an env for new terminal in VSCODE

By default, my Powershell opens base everytime, but I want it to open my specific virtual env for this project. Instead of editing the settings.json in user profile. It is better to create a .vscode folder in the root folder, and then add settings.json inside.

Specify this so that conda activate <env_name> would be run.

{
    "terminal.integrated.profiles.windows": {
    "PowerShell":{
        "source": "PowerShell",
        "args": ["-NoExit", "-Command", "conda activate poetry_uat"]
    }
},
}

# optional
# "terminal.integrated.defaultProfile.windows": "PowerShell"

You could set up multiple profiles, and then could set up a default profile for opening terminal on Windows.

Other Commands

  1. conda env list
  2. conda create -n myenv python=3.8
  3. conda env remove -n myenv

Other Bugs

After Uninstalling the Anaconda…

cmd.exe will likely to break and shows Cmd has exited with error code 1. We need to run

C:\Windows\System32\reg.exe DELETE "HKCU\Software\Microsoft\Command Processor" /v AutoRun /f

which solves the problem.

Yiming Zhang
Yiming Zhang
Quantitative Researcher Associate, JP Morgan