如何在Visual Studio终端中自动激活Python虚拟环境?

3

我正在使用Visual Studio(不是VS Code)开发Python应用程序。

有办法让Visual Studio的开发人员PowerShell自动激活虚拟环境吗?就像在PyCharm或VS-Code中一样。现在,我必须在终端中显式运行命令.\env\Scripts\activate来激活虚拟环境。

1个回答

1

我在设置 PowerShell 启动参数方面找到了一个关键。

进入 Visual Studio 2022 参数 -> 环境 -> 终端。 在 "配置文件" 窗口中点击 PowerShell for developers (Default),然后在参数中按照以下步骤操作:

  1. 添加 -ExecutionPolicy RemoteSigned 在最开始的位置。
  2. 查找 -Command "&{ Command1; Command2; ...; CommandN}" 语法并将 env\Scripts\activate 添加为其中一个命令(使其看起来像 -Command "&{ Command1; Command2; ...; env\Scripts\activate}")。

恭喜!现在每次创建 PowerShell 控制台时,Visual Studio 都会激活您的环境。

注意:

-ExecutionPolicy RemoteSigned 仅设置此特定过程(...每次创建 PowerShell 控制台时运行的过程)的 ExecutionPolicy,并不影响全局、用户或任何其他 env 的 ExecutionPolicy 变量,而是该特定过程中的变量。因此设置是安全的!

P.S. 我们需要更改 ExecutionPolicy 才能运行 activate 脚本。

参考文献:

了解有关 PowerShell 启动参数ExecutionPolicies 的更多信息。


请原谅我的语法,我不是母语使用者 ;) - bc-ru
谢谢你的回答。似乎即使没有 -ExecutionPolicy RemoteSigned 也可以工作。 - SOuser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接