Home > Enterprise >  Conda change environment automatically when changing folder in powershell
Conda change environment automatically when changing folder in powershell

Time:05-19

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?

CodePudding user response:

This is a great use for the prompt function. This get's executed after any operation in PowerShell, and also renders the PowerShell prompt.

Here's the basic one in PowerShell.

function prompt { 'PS '   $(get-location)   '> ' }

Here's a more advanced one, which ships with the awesome DBA Tools PowerShell module.

function Prompt
{
    Write-Host "[" -NoNewline
    Write-Host (Get-Date -Format "HH:mm:ss") -ForegroundColor Gray -NoNewline
    
    try
    {
        $history = Get-History -ErrorAction Ignore
        if ($history)
        {
            Write-Host "][" -NoNewline
            if (([System.Management.Automation.PSTypeName]'Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty').Type)
            {
                Write-Host ([Sqlcollaborative.Dbatools.Utility.DbaTimeSpanPretty]($history[-1].EndExecutionTime - $history[-1].StartExecutionTime)) -ForegroundColor Gray -NoNewline
            }
            else
            {
                Write-Host ($history[-1].EndExecutionTime - $history[-1].StartExecutionTime) -ForegroundColor Gray -NoNewline
            }
        }
    }
    catch { }
    Write-Host "] $($executionContext.SessionState.Path.CurrentLocation.ProviderPath)" -NoNewline
    "> "
}

enter image description here

Now, if you just wanted to take the basic normal prompt and run your code, here is how it would work.

function prompt { 'PS '   $(get-location)   '> ' 
    if ( Test-Path environment.yml ){
        conda_here 
    }
}

This way, your code will automatically run when you change directories. If the directory contains an environment.yml, it will automatically call conda_here for you.

To save this as your default when you launch PowerShell, add it to your PowerShell profile.

CodePudding user response:

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.

  • Related