Python3 VScode

在 VS Code 中安装 Python 扩展、创建并运行调试 Python 文件。

Beginner
Key Points先装 Python 扩展(自带 Pylance),再选解释器;Ctrl+F5 运行、F5 调试,`.vscode/launch.json` 控制调试参数。

安装 Python 扩展

Search the marketplace for Python (published by Microsoft). It pulls in Pylance for completion, type hints and go-to-definition. Add Ruff or Black for formatting and linting.

  • Python — core extension, run/debug/test support
  • Pylance — fast language server with type checking
  • Ruff / Black — linting and formatting

选择解释器

Press Ctrl+Shift+P and run "Python: Select Interpreter" to pick the project venv. The status bar shows the active interpreter; clicking it switches. A wrong interpreter is the most common cause of "it runs the wrong version".

Python
import sys

print(bool(sys.executable))
print(sys.version_info.major)
print(bool(sys.base_prefix))
Output
True
3
True

创建一个 Python 代码文件

Create hello.py; VS Code detects Python and enables highlighting and completion. Save, then click the ▷ button or run python hello.py in the integrated terminal.

Python
import sys


def greet(name: str) -> str:
    return f"Hello, {name}!"


if __name__ == "__main__":
    print(greet("VS Code"))
    print("argv is list:", isinstance(sys.argv, list))
Output
Hello, VS Code!
argv is list: True

运行与调试

Ctrl+F5 runs without debugging; F5 starts the debugger. The first time it asks for the environment (Python File) and writes .vscode/launch.json, where you can set args, env vars and cwd.

Python
import json

cfg = {
    "version": "0.2.0",
    "configurations": [{
        "name": "Python: Current File",
        "type": "debugpy",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
    }],
}

c = cfg["configurations"][0]
print(c["type"], c["request"])
print(c["program"] == "${file}")
print(len(cfg["configurations"]))
Output
debugpy launch
True
1

更多相关工具

Day to day you will also want pytest for tests, jupyter for exploratory work, mypy for static typing and ruff for lint plus format. VS Code has extensions for all of them.

Python
import importlib.util

for name in ('pytest', 'mypy', 'ruff', 'jupyter'):
    print(name, bool(importlib.util.find_spec(name)))
Output
pytest False
mypy False
ruff False
jupyter False
The output above shows these tools are not in the standard library — install them with pip install pytest mypy ruff. False is expected here.

Friends & Partners