0
# Partition Management
1
2
Partition management in pyparted provides detailed control over individual partitions including creation, modification, flag management, and filesystem type handling.
3
4
## Capabilities
5
6
### Partition Class
7
8
The Partition class represents an individual partition within a disk's partition table.
9
10
```python { .api }
11
class Partition:
12
"""
13
Partition represents an individual partition on a disk.
14
Provides access to partition properties and operations.
15
"""
16
17
# Read-only properties
18
disk: Disk # Parent disk object
19
geometry: Geometry # Partition geometry (position and size)
20
fileSystem: FileSystem # Associated filesystem object
21
number: int # Partition number
22
path: str # Device path (e.g. '/dev/sda1')
23
type: int # Partition type constant
24
name: str # Partition name (if supported)
25
active: bool # Whether partition is active/bootable
26
busy: bool # Whether partition is in use by system
27
```
28
29
### Partition Creation
30
31
Constructor for creating new partition objects.
32
33
```python { .api }
34
class Partition:
35
def __init__(disk: Disk, type: int, geometry: Geometry,
36
fs: FileSystem = None) -> Partition:
37
"""
38
Create new partition object.
39
40
Args:
41
disk (Disk): Parent disk object
42
type (int): Partition type constant
43
geometry (Geometry): Partition geometry
44
fs (FileSystem, optional): Filesystem type
45
46
Raises:
47
PartitionException: If partition cannot be created
48
"""
49
```
50
51
### Navigation Methods
52
53
Methods for traversing partitions within a disk.
54
55
```python { .api }
56
class Partition:
57
def nextPartition(start: Partition = None) -> Partition:
58
"""
59
Get next partition on disk after this one.
60
61
Args:
62
start (Partition, optional): Starting partition for search
63
64
Returns:
65
Partition: Next partition or None if at end
66
"""
67
```
68
69
### Partition Properties
70
71
Methods for accessing and modifying partition properties.
72
73
```python { .api }
74
class Partition:
75
def setName(name: str) -> None:
76
"""
77
Set partition name (on labels that support names).
78
79
Args:
80
name (str): Name to set for partition
81
82
Raises:
83
PartitionException: If name cannot be set
84
"""
85
86
def getName() -> str:
87
"""
88
Get partition name (on labels that support names).
89
90
Returns:
91
str: Partition name or None if not supported/set
92
"""
93
94
def resetNumber() -> None:
95
"""
96
Reset partition number (for renumbering operations).
97
98
Raises:
99
PartitionException: If number cannot be reset
100
"""
101
102
def getSize(unit: str = 'MB') -> float:
103
"""
104
Get partition size in specified unit (deprecated, use getLength).
105
106
Args:
107
unit (str): Unit for size ('b', 'kb', 'mb', 'gb', 'tb')
108
109
Returns:
110
float: Partition size in specified unit
111
112
Raises:
113
SyntaxError: If unit is invalid
114
115
Note:
116
This method is deprecated. Use getLength() instead.
117
"""
118
119
def getLength(unit: str = "sectors") -> float:
120
"""
121
Get partition length in sectors or bytes with SI/IEC prefixes.
122
123
Args:
124
unit (str): Unit ('sectors', 'B', 'kB', 'MB', 'GB', 'TB', 'KiB', 'MiB', 'GiB', 'TiB')
125
126
Returns:
127
float: Partition length in specified unit
128
"""
129
```
130
131
### Partition Flags
132
133
Methods for managing partition flags (boot, hidden, etc.).
134
135
```python { .api }
136
class Partition:
137
def getFlag(flag: int) -> bool:
138
"""
139
Get current value of partition flag.
140
141
Args:
142
flag (int): Flag constant to check
143
144
Returns:
145
bool: Current flag value
146
"""
147
148
def setFlag(flag: int) -> None:
149
"""
150
Set partition flag to True.
151
152
Args:
153
flag (int): Flag constant to set
154
155
Raises:
156
PartitionException: If flag cannot be set
157
"""
158
159
def unsetFlag(flag: int) -> None:
160
"""
161
Set partition flag to False.
162
163
Args:
164
flag (int): Flag constant to unset
165
166
Raises:
167
PartitionException: If flag cannot be unset
168
"""
169
170
def isFlagAvailable(flag: int) -> bool:
171
"""
172
Check if flag is supported for this partition.
173
174
Args:
175
flag (int): Flag constant to check
176
177
Returns:
178
bool: True if flag is supported
179
"""
180
```
181
182
### Type ID and UUID Methods
183
184
Methods for managing partition type identifiers (GPT/modern partition tables).
185
186
```python { .api }
187
class Partition:
188
def getTypeId() -> int:
189
"""
190
Get partition type ID as integer (requires parted > 3.5).
191
192
Returns:
193
int: Partition type ID or None if not supported
194
195
Raises:
196
NotImplementedError: If parted version < 3.5
197
PartitionException: If type ID cannot be retrieved
198
"""
199
200
def setTypeId(id: int) -> None:
201
"""
202
Set partition type ID as integer (requires parted > 3.5).
203
204
Args:
205
id (int): Type ID to set
206
207
Raises:
208
NotImplementedError: If parted version < 3.5
209
PartitionException: If type ID cannot be set
210
"""
211
212
def getTypeUuid() -> bytes:
213
"""
214
Get partition type UUID as 16 bytes (requires parted > 3.5).
215
216
Returns:
217
bytes: Partition type UUID or None if not supported
218
219
Raises:
220
NotImplementedError: If parted version < 3.5
221
PartitionException: If type UUID cannot be retrieved
222
"""
223
224
def setTypeUuid(uuid: bytes) -> None:
225
"""
226
Set partition type UUID as 16 bytes (requires parted > 3.5).
227
228
Args:
229
uuid (bytes): Type UUID to set (16 bytes)
230
231
Raises:
232
NotImplementedError: If parted version < 3.5
233
PartitionException: If type UUID cannot be set
234
"""
235
236
# Properties for type identifiers
237
type_id: int # Partition type ID (read/write property)
238
type_uuid: bytes # Partition type UUID (read/write property)
239
```
240
241
### Filesystem and System Type
242
243
Methods for managing partition filesystem type and system type.
244
245
```python { .api }
246
class Partition:
247
def setSystem(fs: FileSystem) -> None:
248
"""
249
Set filesystem type for partition.
250
251
Args:
252
fs (FileSystem): Filesystem object to set
253
254
Raises:
255
PartitionException: If filesystem type cannot be set
256
"""
257
```
258
259
### Partition Names
260
261
Methods for partition name management (supported on GPT and some other formats).
262
263
```python { .api }
264
class Partition:
265
def getName() -> str:
266
"""
267
Get partition name.
268
269
Returns:
270
str: Partition name
271
272
Raises:
273
PartitionException: If names not supported or error occurs
274
"""
275
276
def setName(name: str) -> None:
277
"""
278
Set partition name.
279
280
Args:
281
name (str): New partition name
282
283
Raises:
284
PartitionException: If names not supported or name invalid
285
"""
286
```
287
288
### Advanced Partition Methods
289
290
Additional methods for partition manipulation and information.
291
292
```python { .api }
293
class Partition:
294
def nextPartition() -> Partition:
295
"""
296
Get next partition on disk after this one.
297
298
Returns:
299
Partition: Next partition or None if at end
300
"""
301
302
def getMaxGeometry(constraint: Constraint) -> Geometry:
303
"""
304
Get maximum geometry this partition can be grown to.
305
306
Args:
307
constraint (Constraint): Constraint for growth operation
308
309
Returns:
310
Geometry: Maximum possible geometry
311
312
Raises:
313
PartitionException: If geometry cannot be calculated
314
"""
315
316
def getMaxAvailableSize(unit: str = "MB") -> float:
317
"""
318
Get maximum size this partition can grow to including adjacent free space.
319
320
Args:
321
unit (str): Unit for size ('b', 'kb', 'mb', 'gb', 'tb')
322
323
Returns:
324
float: Maximum available size in specified unit
325
326
Raises:
327
SyntaxError: If unit is invalid
328
"""
329
330
def getFlagsAsString() -> str:
331
"""
332
Get comma-separated string of active partition flags.
333
334
Returns:
335
str: String representation of active flags
336
"""
337
338
def getDeviceNodeName() -> str:
339
"""
340
Get device node name without '/dev/' prefix.
341
342
Returns:
343
str: Device node name (e.g. 'sda1')
344
"""
345
```
346
347
## Usage Examples
348
349
### Creating New Partitions
350
351
```python
352
import parted
353
354
# Get device and create/read disk
355
device = parted.getDevice('/dev/sdb')
356
disk = parted.newDisk(device) # or freshDisk for new partition table
357
358
# Get constraint for partition operations
359
constraint = device.getOptimalAlignedConstraint()
360
361
# Define partition geometry (example: 10GB starting at sector 2048)
362
start_sector = 2048
363
size_sectors = (10 * 1024**3) // device.sectorSize # 10GB in sectors
364
geometry = parted.Geometry(device, start=start_sector, length=size_sectors)
365
366
# Create primary partition
367
partition = parted.Partition(
368
disk=disk,
369
type=parted.PARTITION_NORMAL,
370
geometry=geometry
371
)
372
373
# Add to disk and commit
374
disk.addPartition(partition, constraint)
375
disk.commit()
376
377
print(f"Created partition {partition.number} at {partition.path}")
378
```
379
380
### Managing Partition Flags
381
382
```python
383
import parted
384
385
device = parted.getDevice('/dev/sda')
386
disk = parted.newDisk(device)
387
partition = disk.getPartitionByNumber(1)
388
389
if partition:
390
# Check available flags
391
available_flags = []
392
for flag_name, flag_value in parted.partitionFlag.items():
393
if partition.isFlagAvailable(flag_value):
394
available_flags.append(flag_name)
395
396
print(f"Available flags: {available_flags}")
397
398
# Set boot flag
399
if partition.isFlagAvailable(parted.PARTITION_BOOT):
400
partition.setFlag(parted.PARTITION_BOOT, True)
401
disk.commit()
402
print("Boot flag set")
403
404
# Check current flags
405
boot = partition.getFlag(parted.PARTITION_BOOT)
406
hidden = partition.getFlag(parted.PARTITION_HIDDEN)
407
print(f"Boot: {boot}, Hidden: {hidden}")
408
```
409
410
### Partition Information
411
412
```python
413
import parted
414
415
device = parted.getDevice('/dev/sda')
416
disk = parted.newDisk(device)
417
418
# Display information for all partitions
419
for partition in disk.partitions:
420
print(f"\nPartition {partition.number}:")
421
print(f" Path: {partition.path}")
422
print(f" Type: {partition.type}")
423
print(f" Size: {partition.getSize('GB'):.2f} GB")
424
print(f" Start: {partition.geometry.start}")
425
print(f" End: {partition.geometry.end}")
426
print(f" Active: {partition.active}")
427
print(f" Busy: {partition.isBusy()}")
428
429
# Show filesystem if detected
430
if partition.fileSystem:
431
print(f" Filesystem: {partition.fileSystem.type}")
432
433
# Show name if supported and set
434
try:
435
name = partition.getName()
436
if name:
437
print(f" Name: {name}")
438
except parted.PartitionException:
439
pass # Names not supported on this disk type
440
```
441
442
### Partition Resizing
443
444
```python
445
import parted
446
447
device = parted.getDevice('/dev/sdb')
448
disk = parted.newDisk(device)
449
partition = disk.getPartitionByNumber(1)
450
451
if partition and not partition.isBusy():
452
# Get constraint for operations
453
constraint = device.getOptimalAlignedConstraint()
454
455
# Maximize partition size
456
disk.maximizePartition(partition, constraint)
457
458
# Or set specific geometry
459
new_end = partition.geometry.start + (20 * 1024**3) // device.sectorSize
460
disk.setPartitionGeometry(
461
partition,
462
constraint,
463
partition.geometry.start,
464
new_end
465
)
466
467
disk.commit()
468
print(f"Partition resized to {partition.getSize('GB'):.2f} GB")
469
else:
470
print("Partition is busy or not found")
471
```
472
473
### Working with Extended Partitions
474
475
```python
476
import parted
477
478
device = parted.getDevice('/dev/sda')
479
disk = parted.newDisk(device)
480
481
# Find extended partition (MBR only)
482
extended = disk.getExtendedPartition()
483
if extended:
484
print(f"Extended partition: {extended.number}")
485
486
# List logical partitions
487
logical_partitions = []
488
for partition in disk.partitions:
489
if partition.type == parted.PARTITION_LOGICAL:
490
logical_partitions.append(partition)
491
492
print(f"Logical partitions: {len(logical_partitions)}")
493
for partition in logical_partitions:
494
print(f" {partition.number}: {partition.getSize('GB'):.1f} GB")
495
```
496
497
### Partition Names (GPT)
498
499
```python
500
import parted
501
502
device = parted.getDevice('/dev/sda')
503
disk = parted.newDisk(device)
504
505
# Only works with disk types that support names (like GPT)
506
if disk.supportsFeature(parted.DISK_TYPE_PARTITION_NAME):
507
partition = disk.getPartitionByNumber(1)
508
if partition:
509
try:
510
# Set partition name
511
partition.setName("System Boot")
512
disk.commit()
513
514
# Read name back
515
name = partition.getName()
516
print(f"Partition name: {name}")
517
except parted.PartitionException as e:
518
print(f"Name operation failed: {e}")
519
else:
520
print("Disk type does not support partition names")
521
```
522
523
## Partition Types
524
525
Partition type constants define the role and behavior of partitions:
526
527
### Basic Types
528
- `PARTITION_NORMAL` - Regular primary partition
529
- `PARTITION_LOGICAL` - Logical partition (within extended)
530
- `PARTITION_EXTENDED` - Extended partition container
531
532
### Special Types
533
- `PARTITION_FREESPACE` - Free space region
534
- `PARTITION_METADATA` - Metadata partition
535
- `PARTITION_PROTECTED` - Protected/system partition
536
537
## Partition Flags
538
539
Common partition flags available (support varies by disk type):
540
541
### System Flags
542
- `PARTITION_BOOT` - Boot/active flag
543
- `PARTITION_ROOT` - Root filesystem flag
544
- `PARTITION_SWAP` - Swap partition flag
545
- `PARTITION_HIDDEN` - Hidden partition flag
546
547
### Special Purpose Flags
548
- `PARTITION_RAID` - Software RAID member
549
- `PARTITION_LVM` - LVM physical volume
550
- `PARTITION_LBA` - LBA addressing required
551
- `PARTITION_PREP` - PowerPC PReP boot partition
552
- `PARTITION_ESP` - EFI System Partition
553
- `PARTITION_BIOS_GRUB` - BIOS boot partition for GRUB
554
555
### Microsoft Flags
556
- `PARTITION_MSFT_RESERVED` - Microsoft Reserved partition
557
- `PARTITION_MSFT_DATA` - Microsoft Basic Data partition