# Visual Studio Code 如何运行 Python 脚本

## 简介
在使用 Visual Studio Code 编辑器进行 Python 开发时,如何运行 Python 脚本是初学者常常会遇到的问题。本文将介绍使用 Visual Studio Code 运行 Python 脚本的详细步骤,并附上代码示例。

## 需要的环境
- Visual Studio Code (安装好 Python 插件)
- Python 环境

## 步骤概览
以下是在 Visual Studio Code 中运行 Python 脚本的整体流程:

| 步骤 | 操作 |
|---------------|---------------------------------------|
| 1. 打开 Visual Studio Code | 打开编辑器并创建一个 Python 文件 |
| 2. 配置 Python 解释器 | 配置 Python 解释器路径 |
| 3. 运行 Python 脚本 | 使用 Visual Studio Code 运行 Python 脚本 |

## 详细步骤及代码示例

### 步骤1:打开 Visual Studio Code
打开 Visual Studio Code 编辑器,并创建一个新的 Python 文件。

### 步骤2:配置 Python 解释器
在 Visual Studio Code 编辑器中,我们需要配置 Python 解释器以便正确地运行 Python 脚本。在编辑器底部栏的左下角,可以看到当前编辑器所使用的解释器,如果没有显示需要的解释器,可以点击选择解释器的地方进行设置。

### 步骤3:运行 Python 脚本
在编写好 Python 脚本后,我们可以选择以下几种方式来运行脚本:

#### 1. 使用 Debug 模式
在 Visual Studio Code 中使用 Debug 模式可以方便地运行 Python 脚本,并进行代码调试。在 Python 脚本中设置断点,点击编辑器上方的调试按钮即可开始调试。

```python
# 示例代码
def greet(name):
print(f"Hello, {name}!")

name = "Alice"
greet(name)
```

#### 2. 使用终端运行
另一种方式是通过 Visual Studio Code 自带的终端来运行 Python 脚本。在脚本文件界面右键点击选择“在终端中运行 Python 文件”即可运行脚本。

```bash
# 示例代码
python script.py
```

#### 3. 使用 Code Runner 插件
如果你想更方便地一键运行 Python 脚本,可以安装 Code Runner 插件。安装完插件后,在 Python 脚本文件中点击右键选择“Run Code”即可运行脚本。

```json
// settings.json 中配置 Code Runner
"code-runner.executorMap": {
"python": "python -u"
}
```

通过以上步骤,你就可以在 Visual Studio Code 中成功运行 Python 脚本了。希望这篇文章对你有所帮助!如果有任何问题,欢迎留言询问。