Search code examples
pythonpowershellcondaenvironment

Conda change environment automatically when changing folder in powershell


I use PowerShell and python. As I have multiple project, I have also multiple conda environment.

I want to create a way to automatically change my environment based on the folder. For the moment, I code :

function conda_here {
  $first_line = Get-Content -Head 1 environment.yml  # This returns "name: conda_env_name"
  $env_name = $first_line.Split(": ")[-1]  # This splits it into an array of [name, : , conda_env_name] and takes the last element
  try {
    conda activate $env_name
  } catch {
    Write-Host "Tried to activate environment $env_name, but failed." -ForeGroundColor Red
  }
}

function cda () {
    set-location @args 
    if ( Test-Path environment.yml ){
        conda_here 
    }
}

So I use cda my_folder.

Problem, when I enter directly in the folder (using Pycharm, VSCode or open in with Terminal) the cda doesn't work (it “up to ~”). I will prefer to “override” cd but it doesn't work when changing cda to cd.

Do you have an idea?


Solution

  • Finally, I found a solution when checking around on some "changing CD behavior". Here is my success :

    function conda_here {
      $first_line = Get-Content -Head 1 environment.yml
      $env_name = $first_line.Split(': ')[-1] 
      try { conda activate $env_name }
      catch { Write-Host "Tried to activate environment $env_name, but failed." -ForegroundColor Red }
    }
    
    if (Test-Path environment.yml) { conda_here }
    
    function cda () {
      Set-Location @args 
      if (Test-Path environment.yml) { conda_here }
      else { conda activate Root }    
    }
    
    Set-Item Alias:cd cda
    

    I put this in my $PROFILE

    NB: Root is my conda "basic" (I don't use base) because I use pip package sometimes without specific project/code. You can remove the line or change it if you need.