VS Code-在集成终端中切换Python版本

时间:2020-04-30 04:00:03

标签: python visual-studio-code

我在VS Code v1.44.2计算机上安装了Windows 10,带有Microsoft的vscode-python扩展名。

根据vscode-python文档,它可以在新启动的集成终端窗口中设置正确的python版本。

该功能某种程度上起作用:对我而言,似乎只有从版本选择器中选择的Python版本为3.5.2(Microsoft ML Server附带的版本)时,该功能才起作用。而且,仅当正在启动的集成终端为cmd时,它才有效。

当满足这两个狭窄条件时,可以肯定的是,一旦启动集成终端,vscode-python将运行/path/to/ML Server/Python/executable/activate.bat,如果此后在命令提示符下执行了python --version,您将会看到:

Python 3.5.2 :: Anaconda 4.2.0 (64-bit)

不幸的是,在我安装了其他多个Python版本的情况下,无法激活环境:2.7.x3.6.x3.7.x:不在cmd或{ {1}},我怀疑没有在其他许多外壳上使用

gitbash源代码,原因很明显:vscode-python寻找vscode-python脚本(activateactivate.batactivate.sh )与activate放在同一文件夹中,而这些脚本通常位于python.pythonPath的子目录中。

python.pythonPath/Lib/venv/scripts回购(vscode-python)中的相关代码段复制如下:

src/client/common/terminal/environmentActivationProviders/baseActivationProvider.ts

此方法从 protected async findScriptFile(pythonPath: string, scriptFileNames: string[]): Promise<string | undefined> { const fs = this.serviceContainer.get<IFileSystem>(IFileSystem); for (const scriptFileName of scriptFileNames) { // Generate scripts are found in the same directory as the interpreter. const scriptFile = path.join(path.dirname(pythonPath), scriptFileName); const found = await fs.fileExists(scriptFile); if (found) { return scriptFile; } } } 中调用:

src/client/common/terminal/environmentActivationProviders/bash.ts

从这些代码段可以明显看出,如果集成终端为 public async getActivationCommandsForInterpreter( pythonPath: string, targetShell: TerminalShellType ): Promise<string[] | undefined> { const scriptFile = await this.findScriptFile(pythonPath, this.getScriptsInOrderOfPreference(targetShell)); if (!scriptFile) { return; } return [`source ${scriptFile.fileToCommandArgument()}`]; } private getScriptsInOrderOfPreference(targetShell: TerminalShellType): string[] { switch (targetShell) { case TerminalShellType.wsl: case TerminalShellType.ksh: case TerminalShellType.zsh: case TerminalShellType.gitbash: case TerminalShellType.bash: { return ['activate.sh', 'activate']; } case TerminalShellType.tcshell: case TerminalShellType.cshell: { return ['activate.csh']; } case TerminalShellType.fish: { return ['activate.fish']; } default: { return []; } } } ,则gitbashvscode-python中寻找activate.shactivate,但不在python.pythonPath中寻找其子目录。

我在网上搜索的解决方法并没有带来太多收益。在.bashrc.bash_profile中有一些依赖于别名或源激活的答案,但这并不能解决我的问题。

理想情况下,我希望具有以下功能:

  1. 当我通过VS Code(命令面板或状态栏)设置Python版本时,如果打开了集成终端,它将自动切换版本。我想相同的想法将适用于环境,而不是版本。
  2. 启动集成终端时,应以正确的版本集启动。我可以自动调用适当的activate文件,如果需要的话。

我确定其他vscode-python个用户也遇到了同样的问题,并且从代码段来看,解决方案看起来很简单(允许搜索/venv/**/*);只是想看看是否有其他方法可以实现我的最终目标?

1 个答案:

答案 0 :(得分:0)

没有人回答这个吗? 这是您应该使用的设置的链接。 我在 Windows 上运行 MiniConda3,但您可以为 Mac 调整它。 我为不同的数据科学课程构建了几个环境。当我打开 VS Code 时,终端设置为我想要的 Python 版本。 CMD 提示。还为 Jupyter 或终端窗口设置了正确的版本。

https://medium.com/analytics-vidhya/efficient-way-to-activate-conda-in-vscode-ef21c4c231f2

相关问题