0
# LinuxDistribution Class
1
2
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.
3
4
## Capabilities
5
6
### Class Construction
7
8
Create a LinuxDistribution instance with customizable configuration.
9
10
```python { .api }
11
class LinuxDistribution:
12
def __init__(
13
self,
14
include_lsb: Optional[bool] = None,
15
os_release_file: str = "",
16
distro_release_file: str = "",
17
include_uname: Optional[bool] = None,
18
root_dir: Optional[str] = None,
19
include_oslevel: Optional[bool] = None,
20
) -> None:
21
"""
22
Initialize LinuxDistribution instance.
23
24
Args:
25
include_lsb: Whether to include lsb_release command data
26
None = auto-detect, True = force include, False = exclude
27
os_release_file: Path to custom os-release file (default: auto-detect)
28
distro_release_file: Path to custom distro release file (default: auto-detect)
29
include_uname: Whether to include uname command data
30
None = auto-detect, True = force include, False = exclude
31
root_dir: Custom root directory for file searches (default: /)
32
include_oslevel: Whether to include oslevel command (AIX systems)
33
None = auto-detect, True = force include, False = exclude
34
"""
35
```
36
37
Usage examples:
38
```python
39
from distro import LinuxDistribution
40
41
# Default configuration (same as module-level functions)
42
distro_default = LinuxDistribution()
43
44
# Custom configuration for testing
45
distro_custom = LinuxDistribution(
46
include_lsb=False, # Skip lsb_release command
47
os_release_file="/custom/path/os-release",
48
root_dir="/chroot/environment"
49
)
50
51
# Minimal configuration (os-release only)
52
distro_minimal = LinuxDistribution(
53
include_lsb=False,
54
include_uname=False
55
)
56
```
57
58
### Instance Methods
59
60
All instance methods mirror the module-level functions with identical signatures and behavior.
61
62
#### Core Distribution Information
63
64
```python { .api }
65
def id(self) -> str:
66
"""Return the distribution ID."""
67
68
def name(self, pretty: bool = False) -> str:
69
"""Return the distribution name."""
70
71
def version(self, pretty: bool = False, best: bool = False) -> str:
72
"""Return the distribution version."""
73
74
def codename(self) -> str:
75
"""Return the distribution codename."""
76
77
def like(self) -> str:
78
"""Return space-separated list of like distributions."""
79
80
def info(self, pretty: bool = False, best: bool = False) -> InfoDict:
81
"""Return comprehensive distribution information."""
82
```
83
84
#### Version Components
85
86
```python { .api }
87
def version_parts(self, best: bool = False) -> Tuple[str, str, str]:
88
"""Return version as tuple (major, minor, build_number)."""
89
90
def major_version(self, best: bool = False) -> str:
91
"""Return major version number."""
92
93
def minor_version(self, best: bool = False) -> str:
94
"""Return minor version number."""
95
96
def build_number(self, best: bool = False) -> str:
97
"""Return build number."""
98
```
99
100
#### Data Source Access
101
102
```python { .api }
103
def os_release_info(self) -> Dict[str, str]:
104
"""Return os-release information as dictionary."""
105
106
def lsb_release_info(self) -> Dict[str, str]:
107
"""Return lsb_release information as dictionary."""
108
109
def distro_release_info(self) -> Dict[str, str]:
110
"""Return distro release file information as dictionary."""
111
112
def uname_info(self) -> Dict[str, str]:
113
"""Return uname information as dictionary."""
114
115
def oslevel_info(self) -> str:
116
"""
117
Return oslevel information (AIX systems only).
118
119
Executes 'oslevel' command to get AIX system level information.
120
This method is only functional on AIX systems and returns empty string elsewhere.
121
122
Returns:
123
str: AIX system level information from oslevel command
124
"""
125
126
def os_release_attr(self, attribute: str) -> str:
127
"""Return single attribute from os-release."""
128
129
def lsb_release_attr(self, attribute: str) -> str:
130
"""Return single attribute from lsb_release."""
131
132
def distro_release_attr(self, attribute: str) -> str:
133
"""Return single attribute from distro release file."""
134
135
def uname_attr(self, attribute: str) -> str:
136
"""Return single attribute from uname."""
137
```
138
139
#### Legacy Compatibility
140
141
```python { .api }
142
def linux_distribution(self, full_distribution_name: bool = True) -> Tuple[str, str, str]:
143
"""
144
DEPRECATED: Compatibility method for platform.linux_distribution().
145
146
Args:
147
full_distribution_name: If True, return full name, else short name
148
149
Returns:
150
Tuple[str, str, str]: (name, version, codename)
151
"""
152
```
153
154
### Special Methods
155
156
```python { .api }
157
def __repr__(self) -> str:
158
"""
159
Return string representation of the instance.
160
161
Returns:
162
str: Formatted string with key distribution information
163
"""
164
```
165
166
Usage example:
167
```python
168
from distro import LinuxDistribution
169
170
distro_instance = LinuxDistribution()
171
print(repr(distro_instance))
172
# LinuxDistribution(id='ubuntu', version='20.04', codename='focal')
173
```
174
175
## Use Cases
176
177
### Testing with Custom Files
178
179
```python
180
from distro import LinuxDistribution
181
import tempfile
182
import os
183
184
# Create test os-release file
185
test_os_release = """
186
ID=testdistro
187
NAME="Test Distribution"
188
VERSION="1.0 (Test)"
189
VERSION_ID="1.0"
190
VERSION_CODENAME=test
191
"""
192
193
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='-os-release') as f:
194
f.write(test_os_release)
195
test_file = f.name
196
197
try:
198
# Test with custom file
199
test_distro = LinuxDistribution(
200
os_release_file=test_file,
201
include_lsb=False,
202
include_uname=False
203
)
204
205
print(f"Test ID: {test_distro.id()}") # "testdistro"
206
print(f"Test Name: {test_distro.name()}") # "Test Distribution"
207
print(f"Test Version: {test_distro.version()}") # "1.0"
208
209
finally:
210
os.unlink(test_file)
211
```
212
213
### Multiple Configurations
214
215
```python
216
from distro import LinuxDistribution
217
218
# Production configuration
219
prod_distro = LinuxDistribution()
220
221
# Development configuration (more sources for testing)
222
dev_distro = LinuxDistribution(
223
include_lsb=True, # Force LSB even if slow
224
include_uname=True # Include uname data
225
)
226
227
# Minimal configuration (fastest)
228
fast_distro = LinuxDistribution(
229
include_lsb=False,
230
include_uname=False
231
)
232
233
# Compare results
234
configs = {
235
'production': prod_distro,
236
'development': dev_distro,
237
'fast': fast_distro
238
}
239
240
for name, instance in configs.items():
241
info = instance.info()
242
print(f"{name}: {info['id']} {info['version']}")
243
```
244
245
### Chroot/Container Support
246
247
```python
248
from distro import LinuxDistribution
249
250
# Analyze distribution in chroot environment
251
chroot_distro = LinuxDistribution(
252
root_dir="/path/to/chroot",
253
include_lsb=False, # Commands won't work in chroot
254
include_uname=False
255
)
256
257
print(f"Chroot distribution: {chroot_distro.name()}")
258
```
259
260
### Data Source Filtering
261
262
```python
263
from distro import LinuxDistribution
264
265
# Only use modern standards (os-release)
266
modern_distro = LinuxDistribution(
267
include_lsb=False,
268
include_uname=False
269
)
270
271
# Only use legacy methods (for compatibility testing)
272
legacy_distro = LinuxDistribution(
273
os_release_file="/dev/null", # Force skip os-release
274
include_lsb=True,
275
include_uname=True
276
)
277
278
# Compare modern vs legacy detection
279
print(f"Modern: {modern_distro.id()} {modern_distro.version()}")
280
print(f"Legacy: {legacy_distro.id()} {legacy_distro.version()}")
281
```
282
283
## Performance Considerations
284
285
The LinuxDistribution class uses caching for performance:
286
- Data sources are read only once per instance
287
- Parsed information is cached internally
288
- Multiple method calls reuse cached data
289
290
```python
291
from distro import LinuxDistribution
292
import time
293
294
# Create instance
295
distro_instance = LinuxDistribution()
296
297
# First call reads files and caches results
298
start = time.time()
299
name1 = distro_instance.name()
300
first_call = time.time() - start
301
302
# Subsequent calls use cached data
303
start = time.time()
304
name2 = distro_instance.name()
305
cached_call = time.time() - start
306
307
print(f"First call: {first_call:.4f}s")
308
print(f"Cached call: {cached_call:.4f}s")
309
print(f"Results identical: {name1 == name2}")
310
```
311
312
## Global Instance
313
314
The module-level functions use a global LinuxDistribution instance:
315
316
```python
317
from distro import _distro # Global instance
318
319
# These are equivalent:
320
import distro
321
print(distro.id())
322
print(_distro.id())
323
```