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

标签 python visual-studio virtualenv visual-studio-2022 python-venv

我正在使用 Visual Studio(而非 Visual Studio Code)开发 Python 应用程序。

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

最佳答案

我找到了设置 PowerShell 启动参数的关键。

转到 Visual Studio 2022 参数 -> 环境 -> 终端。 在“配置文件”窗口中,点击PowerShell for developers (Default),然后点击Arguments并执行后续步骤:

  1. 在最开始添加 -ExecutionPolicy RemoteSigned
  2. 查找 -Command "&{ Command1; Command2; ...; CommandN}" 语法和添加 env\Scripts\activate 作为命令之一(所以它看起来像 -Command "&{ Command1; Command2; ...; env\Scripts\activate}")。

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

注意:

-ExecutionPolicy RemoteSigned 仅为这个特定进程设置 ExecutionPolicy(...我们每次创建 PowerShell 控制台时都会运行)并且不会影响全局、用户或任何其他环境 ExecutionPolicy 可变但在此特定过程中可变。所以设置是安全的!

附言我们需要更改 ExecutionPolicy 才能运行 activate 脚本。

引用资料:

阅读有关 PowerShell 的更多信息 startup argumentsExecutionPolicies .

关于python - 如何在 Visual Studio 终端中自动激活 python 虚拟环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72599551/

相关文章:

python - CPython 'overloaded' 函数

python - 在操作中克隆组织内的私有(private) github 存储库

Python、MySQL 使用变量时不插入。可以就地使用变量的精确值,并且它可以工作

c++ - 在 netbeans 中使用 visual studio c++ 编译器

c++ - 这个继承自 std::vector 的类声明有问题吗?

javascript - 尝试通过 RingCentral 通过网页抓取或通过电子邮件发送 .csv 导出来生成自动每日通话报告

c++ - static方法内部使用function时出现LNK2019 unresolved external

virtualenv - 如何使用 pip 从本地缓存安装?

python - 如何在Mac上使用brew在虚拟环境中添加PYTHONPATH?

python - virtualenv 上的 pip 没有在正确的 python 环境中安装包