Visual Studio Code (VS Code)#

注意

这些说明仅指 Anaconda Distribution,但也适用于 Miniconda。

Visual Studio Code (VS Code) 是一个免费的跨平台源代码编辑器,可与 Anaconda Distribution 和 Miniconda 配合使用。安装 Python for Visual Studio Code 扩展使 VS Code 能够连接到 conda 环境的 Python 版本,作为 Python 代码文件的解释器。

提示

更喜欢视觉学习者?登录到 Anaconda Cloud 以遵循我们的使用 VS Code 创建一个简单的 Python 程序

在 Navigator 中启动 VS Code#

安装 VS Code 后,您可以通过单击主页上的 VS Code 磁贴从 Navigator 1.9.12 或更高版本启动应用程序。

当您从 Navigator 启动 VS Code 时,它将自动使用当前所选环境中的 Python 解释器。

创建 conda 环境#

在开始 Python 项目之前,Anaconda 建议创建一个 conda 环境来隔离项目的软件包并管理其依赖项。

  1. 在 VS Code 中打开一个终端。

  2. 通过运行以下命令为您的 Python 项目创建 conda 环境:

    # Replace <ENV_NAME> with your environment name
    # Replace <VERSION> with your desired version of Python
    conda create --name <ENV_NAME> python=<VERSION>
    

注意

如果您未指定 Python 版本,conda 将尝试从其可用通道安装最新版本。

有关使用 conda 管理环境的更多信息,请参阅官方 conda 文档

有关 VS Code 中 Python 环境的更多信息,请参阅 VS Code 官方文档

选择 Anaconda 作为 Python 解释器#

现在,您的 conda 环境已创建,请选择环境的 Python 版本作为解释器。这可确保您的代码能够访问在 conda 环境中安装的特定 Python 版本和软件包中可用的正确代码完成和类型信息。

  1. 打开任何 Python 文件。

  2. 要选择 Python 解释器,请按 Ctrl+Shift+P (Windows、Linux)/Cmd+Shift+P (Mac) 打开命令面板。

  3. 单击 Python:在命令面板中选择解释器,然后选择与您的 Anaconda 环境关联的解释器。

提示

Anaconda 解释器通常显示为 Python。3.x.x('<YOUR_ENV_NAME>':conda)的如果环境的解释器未显示在 Select Interpreter 列表中,请单击 Refresh

您还可以通过选择 Enter interpreter path...(输入解释器路径...)来手动输入解释器路径。

有关在 Anaconda 安装中查找特定解释器路径的更多信息,请参阅查找 Anaconda Python 解释器路径

所选解释器显示在 VS Code 中状态栏的右下角。

测试您的设置#

您现在可以在 VS Code 中执行 Python 函数了!

  1. 创建新的 Python (.py) 文件。

  2. 将以下代码添加到您的文件中:

    # This will display "Hello, World!" in the terminal
     print("Hello, World!")
    
    # This will display your system version in the terminal
    import sys
    print(sys.version)
    
  3. 保存文件。

  4. 单击 Run Python File(运行 Python 文件)。

有关在 VS Code 中使用 Python 的更多信息,请参阅 Visual Studio Code 中的 Python