Distro - an OS platform information API
—
The main class that encapsulates all distribution detection logic with configurable data sources and custom file paths. This class is useful for testing, custom environments, or when you need multiple instances with different configurations.
Create a LinuxDistribution instance with customizable configuration.
class LinuxDistribution:
def __init__(
self,
include_lsb: Optional[bool] = None,
os_release_file: str = "",
distro_release_file: str = "",
include_uname: Optional[bool] = None,
root_dir: Optional[str] = None,
include_oslevel: Optional[bool] = None,
) -> None:
"""
Initialize LinuxDistribution instance.
Args:
include_lsb: Whether to include lsb_release command data
None = auto-detect, True = force include, False = exclude
os_release_file: Path to custom os-release file (default: auto-detect)
distro_release_file: Path to custom distro release file (default: auto-detect)
include_uname: Whether to include uname command data
None = auto-detect, True = force include, False = exclude
root_dir: Custom root directory for file searches (default: /)
include_oslevel: Whether to include oslevel command (AIX systems)
None = auto-detect, True = force include, False = exclude
"""Usage examples:
from distro import LinuxDistribution
# Default configuration (same as module-level functions)
distro_default = LinuxDistribution()
# Custom configuration for testing
distro_custom = LinuxDistribution(
include_lsb=False, # Skip lsb_release command
os_release_file="/custom/path/os-release",
root_dir="/chroot/environment"
)
# Minimal configuration (os-release only)
distro_minimal = LinuxDistribution(
include_lsb=False,
include_uname=False
)All instance methods mirror the module-level functions with identical signatures and behavior.
def id(self) -> str:
"""Return the distribution ID."""
def name(self, pretty: bool = False) -> str:
"""Return the distribution name."""
def version(self, pretty: bool = False, best: bool = False) -> str:
"""Return the distribution version."""
def codename(self) -> str:
"""Return the distribution codename."""
def like(self) -> str:
"""Return space-separated list of like distributions."""
def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
"""Return comprehensive distribution information."""def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
"""Return version as tuple (major, minor, build_number)."""
def major_version(self, best: bool = False) -> str:
"""Return major version number."""
def minor_version(self, best: bool = False) -> str:
"""Return minor version number."""
def build_number(self, best: bool = False) -> str:
"""Return build number."""def os_release_info(self) -> Dict[str, str]:
"""Return os-release information as dictionary."""
def lsb_release_info(self) -> Dict[str, str]:
"""Return lsb_release information as dictionary."""
def distro_release_info(self) -> Dict[str, str]:
"""Return distro release file information as dictionary."""
def uname_info(self) -> Dict[str, str]:
"""Return uname information as dictionary."""
def oslevel_info(self) -> str:
"""
Return oslevel information (AIX systems only).
Executes 'oslevel' command to get AIX system level information.
This method is only functional on AIX systems and returns empty string elsewhere.
Returns:
str: AIX system level information from oslevel command
"""
def os_release_attr(self, attribute: str) -> str:
"""Return single attribute from os-release."""
def lsb_release_attr(self, attribute: str) -> str:
"""Return single attribute from lsb_release."""
def distro_release_attr(self, attribute: str) -> str:
"""Return single attribute from distro release file."""
def uname_attr(self, attribute: str) -> str:
"""Return single attribute from uname."""def linux_distribution(self, full_distribution_name: bool = True) -> Tuple[str, str, str]:
"""
DEPRECATED: Compatibility method for platform.linux_distribution().
Args:
full_distribution_name: If True, return full name, else short name
Returns:
Tuple[str, str, str]: (name, version, codename)
"""def __repr__(self) -> str:
"""
Return string representation of the instance.
Returns:
str: Formatted string with key distribution information
"""Usage example:
from distro import LinuxDistribution
distro_instance = LinuxDistribution()
print(repr(distro_instance))
# LinuxDistribution(id='ubuntu', version='20.04', codename='focal')from distro import LinuxDistribution
import tempfile
import os
# Create test os-release file
test_os_release = """
ID=testdistro
NAME="Test Distribution"
VERSION="1.0 (Test)"
VERSION_ID="1.0"
VERSION_CODENAME=test
"""
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='-os-release') as f:
f.write(test_os_release)
test_file = f.name
try:
# Test with custom file
test_distro = LinuxDistribution(
os_release_file=test_file,
include_lsb=False,
include_uname=False
)
print(f"Test ID: {test_distro.id()}") # "testdistro"
print(f"Test Name: {test_distro.name()}") # "Test Distribution"
print(f"Test Version: {test_distro.version()}") # "1.0"
finally:
os.unlink(test_file)from distro import LinuxDistribution
# Production configuration
prod_distro = LinuxDistribution()
# Development configuration (more sources for testing)
dev_distro = LinuxDistribution(
include_lsb=True, # Force LSB even if slow
include_uname=True # Include uname data
)
# Minimal configuration (fastest)
fast_distro = LinuxDistribution(
include_lsb=False,
include_uname=False
)
# Compare results
configs = {
'production': prod_distro,
'development': dev_distro,
'fast': fast_distro
}
for name, instance in configs.items():
info = instance.info()
print(f"{name}: {info['id']} {info['version']}")from distro import LinuxDistribution
# Analyze distribution in chroot environment
chroot_distro = LinuxDistribution(
root_dir="/path/to/chroot",
include_lsb=False, # Commands won't work in chroot
include_uname=False
)
print(f"Chroot distribution: {chroot_distro.name()}")from distro import LinuxDistribution
# Only use modern standards (os-release)
modern_distro = LinuxDistribution(
include_lsb=False,
include_uname=False
)
# Only use legacy methods (for compatibility testing)
legacy_distro = LinuxDistribution(
os_release_file="/dev/null", # Force skip os-release
include_lsb=True,
include_uname=True
)
# Compare modern vs legacy detection
print(f"Modern: {modern_distro.id()} {modern_distro.version()}")
print(f"Legacy: {legacy_distro.id()} {legacy_distro.version()}")The LinuxDistribution class uses caching for performance:
from distro import LinuxDistribution
import time
# Create instance
distro_instance = LinuxDistribution()
# First call reads files and caches results
start = time.time()
name1 = distro_instance.name()
first_call = time.time() - start
# Subsequent calls use cached data
start = time.time()
name2 = distro_instance.name()
cached_call = time.time() - start
print(f"First call: {first_call:.4f}s")
print(f"Cached call: {cached_call:.4f}s")
print(f"Results identical: {name1 == name2}")The module-level functions use a global LinuxDistribution instance:
from distro import _distro # Global instance
# These are equivalent:
import distro
print(distro.id())
print(_distro.id())Install with Tessl CLI
npx tessl i tessl/pypi-distro