0
# Disk Operations
1
2
Disk operations in pyparted handle partition tables and disk labels. A Disk represents a partitioned storage device and provides methods for reading, creating, and modifying partition tables.
3
4
## Capabilities
5
6
### Disk Creation and Access
7
8
Functions for creating and accessing disk objects with partition tables.
9
10
```python { .api }
11
def newDisk(device: Device) -> Disk:
12
"""
13
Create a Disk object by reading existing partition table from device.
14
15
Args:
16
device (Device): Device object to read from
17
18
Returns:
19
Disk: Disk object with existing partition table
20
21
Raises:
22
DiskException: If no valid partition table found
23
IOException: If device cannot be read
24
"""
25
26
def freshDisk(device: Device, ty: str) -> Disk:
27
"""
28
Create a new Disk object with specified partition table type.
29
WARNING: This creates a new empty partition table.
30
31
Args:
32
device (Device): Device object to create disk on
33
ty (str): Disk type ('gpt', 'msdos', 'mac', etc.)
34
35
Returns:
36
Disk: New disk object with empty partition table
37
38
Raises:
39
DiskException: If disk type is invalid
40
TypeError: If ty parameter is wrong type
41
"""
42
```
43
44
### Disk Class
45
46
The Disk class represents a partition table on a storage device.
47
48
```python { .api }
49
class Disk:
50
"""
51
Disk object describes partitioned storage device.
52
Manages partition table and provides partition operations.
53
"""
54
55
# Read-only properties
56
device: Device # Associated device object
57
type: str # Disk label type ('gpt', 'msdos', etc.)
58
partitions: list[Partition] # List of partitions on disk
59
primaryPartitionCount: int # Number of primary partitions
60
lastPartitionNumber: int # Highest partition number used
61
maxPrimaryPartitionCount: int # Maximum primary partitions allowed
62
maxSupportedPartitionCount: int # Maximum partitions supported by disk type
63
partitionAlignment: Alignment # Partition start address alignment
64
maxPartitionLength: int # Maximum partition length disk label can represent
65
maxPartitionStartSector: int # Maximum start sector disk label can represent
66
```
67
68
### Partition Table Operations
69
70
Methods for managing the overall partition table structure.
71
72
```python { .api }
73
class Disk:
74
def commit() -> None:
75
"""
76
Commit all changes to device and inform OS.
77
Equivalent to commitToDevice() followed by commitToOS().
78
79
Raises:
80
IOException: If commit operation fails
81
"""
82
83
def commitToDevice() -> None:
84
"""
85
Write partition table changes to device.
86
87
Raises:
88
IOException: If write operation fails
89
"""
90
91
def commitToOS() -> None:
92
"""
93
Inform operating system of partition table changes.
94
95
Raises:
96
IOException: If OS notification fails
97
"""
98
99
def check() -> bool:
100
"""
101
Check disk for errors and consistency.
102
103
Returns:
104
bool: True if disk is consistent, False otherwise
105
"""
106
107
def duplicate() -> Disk:
108
"""
109
Create a copy of the disk object.
110
111
Returns:
112
Disk: Duplicated disk object
113
114
Raises:
115
CreateException: If duplication fails
116
"""
117
118
def destroy() -> None:
119
"""
120
Destroy disk object and free resources.
121
"""
122
```
123
124
### Partition Management
125
126
Methods for adding, removing, and modifying partitions.
127
128
```python { .api }
129
class Disk:
130
def addPartition(partition: Partition, constraint: Constraint) -> None:
131
"""
132
Add partition to disk using specified constraint.
133
134
Args:
135
partition (Partition): Partition to add
136
constraint (Constraint): Constraint for partition placement
137
138
Raises:
139
PartitionException: If partition cannot be added
140
ConstraintException: If constraint cannot be satisfied
141
"""
142
143
def removePartition(partition: Partition) -> None:
144
"""
145
Remove partition from disk (but don't delete from device).
146
147
Args:
148
partition (Partition): Partition to remove
149
150
Raises:
151
PartitionException: If partition cannot be removed
152
"""
153
154
def deletePartition(partition: Partition) -> None:
155
"""
156
Delete partition from disk and device.
157
158
Args:
159
partition (Partition): Partition to delete
160
161
Raises:
162
PartitionException: If partition cannot be deleted
163
"""
164
165
def deleteAllPartitions() -> None:
166
"""
167
Delete all partitions from disk.
168
169
Raises:
170
PartitionException: If partitions cannot be deleted
171
"""
172
```
173
174
### Partition Queries
175
176
Methods for finding and accessing partitions.
177
178
```python { .api }
179
class Disk:
180
def getFirstPartition() -> Partition:
181
"""
182
Get first partition on disk.
183
184
Returns:
185
Partition: First partition or None if no partitions
186
"""
187
188
def getPartitionBySector(sector: int) -> Partition:
189
"""
190
Get partition containing the specified sector.
191
192
Args:
193
sector (int): Sector number to check
194
195
Returns:
196
Partition: Partition containing sector or None
197
"""
198
199
def getExtendedPartition() -> Partition:
200
"""
201
Get extended partition (for MBR disks).
202
203
Returns:
204
Partition: Extended partition or None if not present
205
"""
206
207
def getPartitionByPath(path: str) -> Partition:
208
"""
209
Get partition by device path.
210
211
Args:
212
path (str): Device path (e.g. '/dev/sda1')
213
214
Returns:
215
Partition: Partition with specified path or None
216
"""
217
```
218
219
### Partition Type Queries
220
221
Methods for getting partitions by type or property.
222
223
```python { .api }
224
class Disk:
225
def getLogicalPartitions() -> list[Partition]:
226
"""
227
Get list of logical partitions (MBR disks).
228
229
Returns:
230
list[Partition]: List of logical partitions
231
"""
232
233
def getPrimaryPartitions() -> list[Partition]:
234
"""
235
Get list of primary partitions.
236
237
Returns:
238
list[Partition]: List of primary partitions
239
"""
240
241
def getRaidPartitions() -> list[Partition]:
242
"""
243
Get list of partitions with RAID flag set.
244
245
Returns:
246
list[Partition]: List of RAID partitions
247
"""
248
249
def getLVMPartitions() -> list[Partition]:
250
"""
251
Get list of partitions with LVM flag set.
252
253
Returns:
254
list[Partition]: List of LVM partitions
255
"""
256
```
257
258
### Free Space Queries
259
260
Methods for finding available free space on the disk.
261
262
```python { .api }
263
class Disk:
264
def getFreeSpaceRegions() -> list[Geometry]:
265
"""
266
Get list of Geometry objects representing free space regions.
267
268
Returns:
269
list[Geometry]: List of free space geometries
270
"""
271
272
def getFreeSpacePartitions() -> list[Partition]:
273
"""
274
Get list of Partition objects representing free space regions.
275
276
Returns:
277
list[Partition]: List of free space partitions
278
"""
279
```
280
281
### Partition Geometry Operations
282
283
Methods for modifying partition sizes and positions.
284
285
```python { .api }
286
class Disk:
287
def setPartitionGeometry(partition: Partition, constraint: Constraint,
288
start: int, end: int) -> None:
289
"""
290
Set partition geometry within constraint.
291
292
Args:
293
partition (Partition): Partition to modify
294
constraint (Constraint): Constraint for operation
295
start (int): New start sector
296
end (int): New end sector
297
298
Raises:
299
PartitionException: If geometry cannot be set
300
ConstraintException: If constraint violated
301
"""
302
303
def maximizePartition(partition: Partition, constraint: Constraint) -> None:
304
"""
305
Maximize partition size within constraint.
306
307
Args:
308
partition (Partition): Partition to maximize
309
constraint (Constraint): Constraint for operation
310
311
Raises:
312
PartitionException: If partition cannot be maximized
313
ConstraintException: If constraint violated
314
"""
315
316
def calculateMaxPartitionGeometry(partition: Partition,
317
constraint: Constraint = None) -> Geometry:
318
"""
319
Get maximum possible geometry for partition.
320
321
Args:
322
partition (Partition): Partition to check
323
constraint (Constraint, optional): Constraint for operation
324
325
Returns:
326
Geometry: Maximum geometry possible
327
328
Raises:
329
ConstraintException: If no solution exists
330
"""
331
332
def minimizeExtendedPartition() -> None:
333
"""
334
Minimize extended partition to fit logical partitions.
335
336
Raises:
337
PartitionException: If operation fails
338
"""
339
```
340
341
### Disk Flags
342
343
Methods for managing disk-level flags and properties.
344
345
```python { .api }
346
class Disk:
347
def getFlag(flag: int) -> bool:
348
"""
349
Get value of disk flag.
350
351
Args:
352
flag (int): Flag constant to check
353
354
Returns:
355
bool: Current flag value
356
"""
357
358
def setFlag(flag: int) -> None:
359
"""
360
Set disk flag to True.
361
362
Args:
363
flag (int): Flag constant to set
364
365
Raises:
366
DiskException: If flag cannot be set
367
"""
368
369
def unsetFlag(flag: int) -> None:
370
"""
371
Set disk flag to False.
372
373
Args:
374
flag (int): Flag constant to unset
375
376
Raises:
377
DiskException: If flag cannot be unset
378
"""
379
380
def isFlagAvailable(flag: int) -> bool:
381
"""
382
Check if flag is available for this disk type.
383
384
Args:
385
flag (int): Flag constant to check
386
387
Returns:
388
bool: True if flag is supported
389
"""
390
```
391
392
### Disk Type Information
393
394
Methods for querying disk type capabilities.
395
396
```python { .api }
397
class Disk:
398
def supportsFeature(feature: int) -> bool:
399
"""
400
Check if disk type supports specified feature.
401
402
Args:
403
feature (int): Feature constant to check
404
405
Returns:
406
bool: True if feature is supported
407
"""
408
```
409
410
## Usage Examples
411
412
### Reading Existing Partition Table
413
414
```python
415
import parted
416
417
# Read existing partition table
418
device = parted.getDevice('/dev/sda')
419
disk = parted.newDisk(device)
420
421
print(f"Disk type: {disk.type}")
422
print(f"Number of partitions: {len(disk.partitions)}")
423
print(f"Primary partitions: {disk.primaryPartitionCount}")
424
425
# List all partitions
426
for partition in disk.partitions:
427
size_mb = partition.getSize('MB')
428
print(f"Partition {partition.number}: {size_mb:.1f} MB")
429
```
430
431
### Creating New Partition Table
432
433
```python
434
import parted
435
436
# WARNING: This destroys existing data
437
device = parted.getDevice('/dev/sdb')
438
439
# Create new GPT partition table
440
disk = parted.freshDisk(device, 'gpt')
441
442
# Get device constraint for partition operations
443
constraint = device.getConstraint()
444
445
# Create geometry for new partition (example: use first 10GB)
446
sectors_per_gb = (1024**3) // device.sectorSize
447
geometry = parted.Geometry(device, start=2048, length=sectors_per_gb * 10)
448
449
# Create new partition
450
partition = parted.Partition(
451
disk=disk,
452
type=parted.PARTITION_NORMAL,
453
geometry=geometry
454
)
455
456
# Add partition to disk
457
disk.addPartition(partition, constraint)
458
459
# Commit changes
460
disk.commit()
461
```
462
463
### Partition Table Modifications
464
465
```python
466
import parted
467
468
device = parted.getDevice('/dev/sdc')
469
disk = parted.newDisk(device)
470
471
# Find partition to modify
472
partition = disk.getPartitionByNumber(1)
473
if partition:
474
# Get optimal constraint
475
constraint = device.getOptimalAlignedConstraint()
476
477
# Maximize partition size
478
disk.maximizePartition(partition, constraint)
479
480
# Commit changes
481
disk.commitToDevice()
482
disk.commitToOS()
483
```
484
485
### Disk Information and Validation
486
487
```python
488
import parted
489
490
device = parted.getDevice('/dev/sda')
491
disk = parted.newDisk(device)
492
493
# Check disk consistency
494
if not disk.check():
495
print("Warning: Disk has consistency issues")
496
497
# Display disk capabilities
498
print(f"Max primary partitions: {disk.maxPrimaryPartitionCount}")
499
print(f"Supports extended partitions: {disk.supportsFeature(parted.DISK_TYPE_EXTENDED)}")
500
print(f"Supports partition names: {disk.supportsFeature(parted.DISK_TYPE_PARTITION_NAME)}")
501
502
# Check disk flags
503
if disk.isFlagAvailable(parted.DISK_GPT_PMBR_BOOT):
504
boot_flag = disk.getFlag(parted.DISK_GPT_PMBR_BOOT)
505
print(f"GPT PMBR boot flag: {boot_flag}")
506
```
507
508
## Disk Types
509
510
Common disk label types supported by pyparted:
511
512
- **'gpt'** - GUID Partition Table (modern, recommended)
513
- **'msdos'** - Master Boot Record / DOS partition table
514
- **'mac'** - Apple partition map
515
- **'bsd'** - BSD disklabel
516
- **'sun'** - Sun disk label
517
- **'dasd'** - S/390 DASD partition table
518
519
Use `parted.getLabels()` to get supported types for current architecture.