0
# Device Management
1
2
Device management in pyparted provides access to physical storage devices and their properties. Devices represent the hardware-level interface to disks, SSDs, and other storage media.
3
4
## Capabilities
5
6
### Device Discovery
7
8
Functions for discovering and accessing storage devices in the system.
9
10
```python { .api }
11
def getDevice(path: str) -> Device:
12
"""
13
Get a Device object for the specified device path.
14
15
Args:
16
path (str): Operating system path to device node (e.g. '/dev/sda')
17
18
Returns:
19
Device: Device object for the specified path
20
21
Raises:
22
DeviceException: If invalid path is provided
23
"""
24
25
def getAllDevices() -> list[Device]:
26
"""
27
Return a list of Device objects for all devices in the system.
28
29
Returns:
30
list[Device]: List of all detected devices
31
"""
32
33
def freeAllDevices() -> None:
34
"""
35
Free all Device objects. Generally not needed in normal usage.
36
"""
37
```
38
39
### Device Class
40
41
The Device class represents a physical storage device with comprehensive properties and methods.
42
43
```python { .api }
44
class Device:
45
"""
46
Device represents a physical piece of hardware in the system.
47
Provides low-level, operating system specific interface to hardware.
48
"""
49
50
# Read-only properties
51
model: str # Model name and vendor of device
52
path: str # Filesystem node path (e.g. '/dev/sda')
53
type: int # Device type constant (DEVICE_SCSI, DEVICE_IDE, etc.)
54
sectorSize: int # Logical sector size in bytes
55
physicalSectorSize: int # Physical sector size in bytes
56
length: int # Device size in sectors
57
openCount: int # Number of times device has been opened
58
readOnly: bool # Read-only status
59
externalMode: bool # External mode status
60
dirty: bool # Dirty status
61
bootDirty: bool # Boot sector dirty status
62
host: int # SCSI host ID
63
did: int # SCSI device ID
64
busy: bool # Whether device is in use
65
hardwareGeometry: tuple # Hardware CHS geometry (cylinders, heads, sectors)
66
biosGeometry: tuple # BIOS CHS geometry (cylinders, heads, sectors)
67
minimumAlignment: Alignment # Minimum alignment for this device
68
optimumAlignment: Alignment # Optimum alignment for this device
69
```
70
71
### Device Operations
72
73
Methods for device I/O and management operations.
74
75
```python { .api }
76
class Device:
77
def open() -> None:
78
"""
79
Open device for I/O operations.
80
81
Raises:
82
IOException: If device cannot be opened
83
"""
84
85
def close() -> None:
86
"""
87
Close device after I/O operations.
88
89
Raises:
90
IOException: If device cannot be closed
91
"""
92
93
def clobber() -> None:
94
"""
95
Remove existing disk label from device.
96
WARNING: This destroys the partition table.
97
98
Raises:
99
IOException: If operation fails
100
"""
101
102
def removeFromCache() -> None:
103
"""
104
Remove device from internal cache.
105
"""
106
107
def destroy() -> None:
108
"""
109
Destroy device object and free resources.
110
"""
111
112
def beginExternalAccess() -> None:
113
"""
114
Set up device for use by external program.
115
Call before running external programs on device.
116
117
Raises:
118
IOException: If external access cannot be enabled
119
"""
120
121
def endExternalAccess() -> None:
122
"""
123
Turn off external access mode for device.
124
Call after external program finishes using device.
125
126
Raises:
127
IOException: If external access cannot be disabled
128
"""
129
```
130
131
### Device I/O Operations
132
133
Low-level read/write operations on devices.
134
135
```python { .api }
136
class Device:
137
def read(start: int, count: int) -> bytes:
138
"""
139
Read sectors from device.
140
141
Args:
142
start (int): Starting sector number
143
count (int): Number of sectors to read
144
145
Returns:
146
bytes: Data read from device
147
148
Raises:
149
IOException: If read operation fails
150
"""
151
152
def write(buffer: bytes, start: int, count: int) -> None:
153
"""
154
Write sectors to device.
155
156
Args:
157
buffer (bytes): Data to write
158
start (int): Starting sector number
159
count (int): Number of sectors to write
160
161
Raises:
162
IOException: If write operation fails
163
"""
164
165
def sync(fast: bool = False) -> None:
166
"""
167
Synchronize device, ensuring all writes are committed.
168
169
Args:
170
fast (bool): If True, perform fast sync; if False, full sync
171
172
Raises:
173
IOException: If sync operation fails
174
"""
175
176
def check(start: int, count: int) -> bool:
177
"""
178
Check device sectors for errors.
179
180
Args:
181
start (int): Starting sector number
182
count (int): Number of sectors to check
183
184
Returns:
185
bool: True if sectors are healthy, False otherwise
186
187
Raises:
188
IOException: If check operation fails
189
"""
190
```
191
192
### Size and Conversion Methods
193
194
Methods for getting device size and converting between units.
195
196
```python { .api }
197
class Device:
198
def getSize(unit: str = "MB") -> float:
199
"""
200
Get device size in specified unit (deprecated, use getLength).
201
202
Args:
203
unit (str): Unit string ('b', 'kb', 'mb', 'gb', 'tb')
204
205
Returns:
206
float: Device size in specified unit
207
208
Raises:
209
SyntaxError: If invalid unit specified
210
211
Note:
212
This method is deprecated. Use getLength() instead.
213
"""
214
215
def getLength(unit: str = "sectors") -> float:
216
"""
217
Get device length in sectors or bytes with SI/IEC prefixes.
218
219
Args:
220
unit (str): Unit ('sectors', 'B', 'kB', 'MB', 'GB', 'TB', 'KiB', 'MiB', 'GiB', 'TiB')
221
222
Returns:
223
float: Device length in specified unit
224
"""
225
```
226
227
### Sector/Cylinder Conversion Methods
228
229
Methods for converting between sector and cylinder addressing.
230
231
```python { .api }
232
class Device:
233
def startSectorToCylinder(sector: int) -> int:
234
"""
235
Convert start sector number to cylinder number.
236
237
Args:
238
sector (int): Sector number
239
240
Returns:
241
int: Cylinder number
242
"""
243
244
def endSectorToCylinder(sector: int) -> int:
245
"""
246
Convert end sector number to cylinder number.
247
248
Args:
249
sector (int): Sector number
250
251
Returns:
252
int: Cylinder number
253
"""
254
255
def startCylinderToSector(cylinder: int) -> int:
256
"""
257
Convert cylinder number to start sector number.
258
259
Args:
260
cylinder (int): Cylinder number
261
262
Returns:
263
int: Start sector number
264
"""
265
266
def endCylinderToSector(cylinder: int) -> int:
267
"""
268
Convert cylinder number to end sector number.
269
270
Args:
271
cylinder (int): Cylinder number
272
273
Returns:
274
int: End sector number
275
"""
276
```
277
278
### Constraint and Alignment
279
280
Methods and properties for obtaining device-specific constraint and alignment information.
281
282
```python { .api }
283
class Device:
284
def getConstraint() -> Constraint:
285
"""
286
Get constraint that accepts any region on this device.
287
288
Returns:
289
Constraint: Device constraint object
290
291
Raises:
292
CreateException: If constraint creation fails
293
"""
294
295
def getMinimumAlignment() -> Alignment:
296
"""
297
Get minimum alignment required by device.
298
299
Returns:
300
Alignment: Minimum alignment object
301
"""
302
303
def getOptimumAlignment() -> Alignment:
304
"""
305
Get optimum alignment for best device performance.
306
307
Returns:
308
Alignment: Optimum alignment object
309
"""
310
311
# Properties for alignment constraints
312
minimalAlignedConstraint: Constraint # Constraint with minimal alignment requirements
313
optimalAlignedConstraint: Constraint # Constraint with optimal alignment requirements
314
```
315
316
## Usage Examples
317
318
### Basic Device Information
319
320
```python
321
import parted
322
323
# Get device information
324
device = parted.getDevice('/dev/sda')
325
print(f"Model: {device.model}")
326
print(f"Size: {device.length * device.sectorSize / (1024**3):.1f} GB")
327
print(f"Sector size: {device.sectorSize} bytes")
328
print(f"Physical sector size: {device.physicalSectorSize} bytes")
329
print(f"Read-only: {device.readOnly}")
330
print(f"Busy: {device.busy}")
331
```
332
333
### List All Devices
334
335
```python
336
import parted
337
338
# List all storage devices
339
for device in parted.getAllDevices():
340
size_gb = device.length * device.sectorSize / (1024**3)
341
print(f"{device.path}: {device.model} ({size_gb:.1f} GB)")
342
```
343
344
### Safe Device Operations
345
346
```python
347
import parted
348
349
try:
350
device = parted.getDevice('/dev/sdb')
351
352
# Check if device is safe to modify
353
if device.busy:
354
print("Device is busy, cannot modify")
355
return
356
357
if device.readOnly:
358
print("Device is read-only, cannot modify")
359
return
360
361
# Perform operations
362
device.open()
363
try:
364
# ... perform I/O operations
365
device.sync()
366
finally:
367
device.close()
368
369
except parted.DeviceException as e:
370
print(f"Device error: {e}")
371
except parted.IOException as e:
372
print(f"I/O error: {e}")
373
```
374
375
## Device Types
376
377
Device type constants identify different storage device interfaces:
378
379
- `DEVICE_SCSI` - SCSI devices
380
- `DEVICE_IDE` - IDE/PATA devices
381
- `DEVICE_NVME` - NVMe devices
382
- `DEVICE_VIRTBLK` - Virtual block devices
383
- `DEVICE_DM` - Device mapper devices
384
- `DEVICE_FILE` - File-based devices
385
- `DEVICE_UNKNOWN` - Unknown device types