驻仁 發表於 2025-5-17 15:07:16

PowerShell 实现 conda 懒加载的问题及解决方案

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">问题</a></li><li><a href="#_label1">解决方案</a></li></ul></div><p class="maodian"><a name="_label0"></a></p><h2>问题</h2>
<p>执行命令<code>conda init powershell</code>会在 <code>profile.ps1</code>中添加conda初始化的命令。<br />即使用户不需要用到conda,也会初始化conda环境,拖慢PowerShell的启动速度。</p>
<p class="maodian"><a name="_label1"></a></p><h2>解决方案</h2>
<p>本文展示了如何实现conda的懒加载,默认不加载conda环境,只有在用户执行conda命令时才加载。</p>
<p>(1) Path环境变量添加conda路径</p>
<ul><li>添加conda3的本地路径:D:\code\miniconda3</li><li>添加conda3的脚本路径:D:\code\miniconda3\Scripts</li></ul>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202505/2025051715001530.png" /></p>
<p>(2) 注销conda初始化命令</p>
<ul><li>进入文件夹:C:\Users&lt;user_name&gt;\Documents\WindowsPowerShell</li><li>编辑<code>profile.ps1</code>文件,注释或删除conda初始化代码</li></ul>
<div class="jb51code"><pre class="brush:ps;">#region conda initialize
# !! Contents within this block are managed by 'conda init' !!
# If (Test-Path "D:\code\miniconda3\Scripts\conda.exe") {
#    (&amp; "D:\code\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression
# }
#endregion</pre></div>
<p>(3) 封装conda命令,实现懒加载</p>
<ul><li>进入文件夹:C:\Users&lt;user_name&gt;\Documents\WindowsPowerShell</li><li>编辑<code>Microsoft.PowerShell_profile.ps1</code>文件,添加代码。</li></ul>
<div class="jb51code"><pre class="brush:ps;">function Load-Conda {
    If (Test-Path "D:\code\miniconda3\Scripts\conda.exe") {
      (&amp; "D:\code\miniconda3\Scripts\conda.exe" "shell.powershell" "hook") | Out-String | ?{$_} | Invoke-Expression
    }
    conda @args
}
Set-Alias conda Load-Conda</pre></div>
頁: [1]
查看完整版本: PowerShell 实现 conda 懒加载的问题及解决方案