On this page
  1. site
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Adding a Package Directory and Processing Its .pth Files
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

site

Prev: signal | Up: stdlib_module | Next: smtplib
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — site
Tags: #public #python3 #stdlib


Import

import site

Overview

Startup configuration module automatically imported during Python initialization to populate sys.path with site-packages, process .pth files, detect virtual environments (sys.prefix vs sys.base_prefix), and register sitecustomize / usercustomize. Use site programmatically to query site-packages locations (getsitepackages(), getusersitepackages()) or add .pth-aware directories via addsitedir().

Quick Start

import site

# Inspect where third-party packages are installed for this interpreter
system_dirs = site.getsitepackages()
user_dir = site.getusersitepackages()
assert isinstance(system_dirs, list) and len(system_dirs) >= 1
assert isinstance(user_dir, str)

Implementation Walkthrough

1. Adding a Package Directory and Processing Its .pth Files

Unlike sys.path.append(), site.addsitedir() also evaluates any .pth files inside the added directory (needed for editable installs and namespace hooks):

import site
from pathlib import Path
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    extra = Path(tmp) / "vendor"
    extra.mkdir()
    site.addsitedir(str(extra))

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes