Python3 环境搭建

Python3 下载安装、环境变量配置、运行 Python 与常用配套工具。

Beginner
Key Points装 Python 时务必勾选 Add to PATH;用 python --version 和 pip --version 验证;虚拟环境隔离项目依赖。

Python3 下载

Get the installer for your platform from python.org's Downloads page: 64-bit installer on Windows, universal2 on macOS; on Linux the package manager usually provides it. Pick the current stable release, not a preview.

  • Windows — python-3.x.x-amd64.exe
  • macOS — python-3.x.x-macos11.pkg
  • Linux — apt / dnf / pacman install python3

Python 安装

On the first screen of the Windows installer, tick "Add Python to PATH" — otherwise the shell cannot find python. Under Customize you can also enable pip and tcl/tk.

Python
import sys
import os
import platform

print("executable:", os.path.basename(sys.executable))
print("platform:", platform.system())
print("prefix set:", bool(sys.prefix))
Output
executable: python.exe
platform: Windows
prefix set: True

环境变量配置

PATH must contain both the Python install directory and its Scripts directory: the first gives you python, the second pip. Verify in a new terminal — an already-open one keeps the old environment.

Python
import os
import sys

paths = os.environ.get('PATH', '').split(os.pathsep)
has_python = any('python' in p.lower() for p in paths)
print("path entries:", len(paths) > 0)
print("python in PATH:", has_python)
print("sys.path entries:", len(sys.path) > 0)
Output
path entries: True
python in PATH: True
sys.path entries: True
PATH lets the shell find executables; sys.path lets import find modules. They are unrelated — do not edit PATH to fix an import error.

运行 Python

Three ways to run: interactive python, script python hello.py, module python -m http.server. -c executes a string directly — handy for quick checks.

Python
import subprocess
import sys

r1 = subprocess.run([sys.executable, '-c', 'print(1 + 1)'],
                    capture_output=True, text=True)
print("stdout:", r1.stdout.strip())
print("returncode:", r1.returncode)

r2 = subprocess.run([sys.executable, '-c', 'raise SystemExit(3)'],
                    capture_output=True, text=True)
print("exit on error:", r2.returncode)
Output
stdout: 2
returncode: 0
exit on error: 3

更多必备工具

After the interpreter you need three things: pip for packages, venv for per-project isolation, and pipx for command-line tools. For editors, VS Code and PyCharm both have first-class Python support.

Python
import sys
import ensurepip

print("pip available:", ensurepip.version() != '')
print("venv available:", 'venv' in sys.stdlib_module_names)
print("ensurepip parsed:", ensurepip.version().count('.') >= 1)
Output
pip available: True
venv available: True
ensurepip parsed: True

Friends & Partners