pyenv-win / pyenv-win-venv

A CLI to manage virtual envs with pyenv-win
Apache License 2.0
77 stars 8 forks source link

Automatically detect .python-version and switch in/out of enviroment when changing directories #19

Open sam-val opened 9 months ago

sam-val commented 9 months ago

Like title, current version (v0.6.2) doesn't do this. It'd be great if we also have it too like the original.

arzkar commented 9 months ago

The current behavior is to activate the env if you open a shell from within a directory which has the .python-version. To automatically look for the env in every directory, I will need to add an Event Watcher which will check for the .python-version every time we change the directory, might add an overhead to the shell but I will look into it when I get the time.

bucefalog commented 3 weeks ago

If anybody lands on this page, adding the following lines to powershell's profile might work as a provisory solution:

# ACTIVE PYTHON ENVIRONMENT AUTOMATICALLY:
$script_file = "$HOME/.config/powershell/set_location_proxy.ps1"
#  NOTE: the following should only be executed once and the regex substitution may fail in the future
$temp_var = New-Object System.Management.Automation.CommandMetadata (Get-Command Set-Location)
$temp_var = [System.Management.Automation.ProxyCommand]::Create($temp_var)
$temp_var = ($temp_var) -replace '(\s*)\$steppablePipeline\.End\(\)', "`${1}`$steppablePipeline.End()`r`n`${1}pyenv-venv init root" 
"function Set-Location {`n" | Set-Content -Path "$script_file" 
$temp_var | Add-Content -Path "$script_file" 
"`n}" | Add-Content -Path "$script_file"
. "$script_file"

The script is creating a proxy to the Set-Location function and sourcing it. The proxy replaces the powershell default function and works with any command that uses the function (including cd and zoxide). It may also be useful to modify the code to deactivate the current environment when moving into a folder with no python version found.