半自动化激活 Python venv
- Powershell 启动时会自动加载这个文件,
C:\Users\xyz\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
,因此可以在这里定义一个简单的 cmdlet 找到系统中的虚拟环境,根据用户选择直接激活.
# 这里有 Python venv 指定在这里找
$global:Dirs = @("C:\\Python", "D:\\Somewhere-else")
function Myvenv {
# 列举 $Dirs 中存在的 venv, 用户选择编号后直接激活
$venv_list = Get-ChildItem -Path $Dirs -recurse -Depth 2 | where {($_.psiscontainer) -AND $_.name -match 'venv'} | % {$_.FullName}
for($i = 0; $i -lt $venv_list.count; $i++) {
Write-Host "${i}: $($venv_list[$i])"
}
Write-Host "$($venv_list.count) venv(s) found. Pick one: " -ForegroundColor Green
$v = Read-Host
$venv_home = $venv_list[$v]
if ((Test-Path "$venv_home\Scripts") -eq "True") {
Invoke-Expression "$venv_home\Scripts\activate.ps1"
} else {
Write-Host "$venv_home doesn't contain a virtualenv"
}
}
示例
Windows PowerShell
版权所有 © Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\xyz> Myvenv
0: C:\Python\pyvenv310
1: C:\Python\pyvenv312
2: D:\Somewhere-else\venv
3 venv(s) found. Pick one:
1
C:\Python\pyvenv312 doesn’t contain a virtualenv # 实际上这里是个空目录
PS C:\Users\xyz> Myvenv
0: C:\Python\pyvenv310
1: C:\Python\pyvenv312
2: D:\Somewhere-else\venv
3 venv(s) found. Pick one:
0
(pyvenv310) PS C:\Users\xyz>