Python bindings for GNU parted library providing disk partition management capabilities
—
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.
Functions for creating and accessing disk objects with partition tables.
def newDisk(device: Device) -> Disk:
"""
Create a Disk object by reading existing partition table from device.
Args:
device (Device): Device object to read from
Returns:
Disk: Disk object with existing partition table
Raises:
DiskException: If no valid partition table found
IOException: If device cannot be read
"""
def freshDisk(device: Device, ty: str) -> Disk:
"""
Create a new Disk object with specified partition table type.
WARNING: This creates a new empty partition table.
Args:
device (Device): Device object to create disk on
ty (str): Disk type ('gpt', 'msdos', 'mac', etc.)
Returns:
Disk: New disk object with empty partition table
Raises:
DiskException: If disk type is invalid
TypeError: If ty parameter is wrong type
"""The Disk class represents a partition table on a storage device.
class Disk:
"""
Disk object describes partitioned storage device.
Manages partition table and provides partition operations.
"""
# Read-only properties
device: Device # Associated device object
type: str # Disk label type ('gpt', 'msdos', etc.)
partitions: list[Partition] # List of partitions on disk
primaryPartitionCount: int # Number of primary partitions
lastPartitionNumber: int # Highest partition number used
maxPrimaryPartitionCount: int # Maximum primary partitions allowed
maxSupportedPartitionCount: int # Maximum partitions supported by disk type
partitionAlignment: Alignment # Partition start address alignment
maxPartitionLength: int # Maximum partition length disk label can represent
maxPartitionStartSector: int # Maximum start sector disk label can representMethods for managing the overall partition table structure.
class Disk:
def commit() -> None:
"""
Commit all changes to device and inform OS.
Equivalent to commitToDevice() followed by commitToOS().
Raises:
IOException: If commit operation fails
"""
def commitToDevice() -> None:
"""
Write partition table changes to device.
Raises:
IOException: If write operation fails
"""
def commitToOS() -> None:
"""
Inform operating system of partition table changes.
Raises:
IOException: If OS notification fails
"""
def check() -> bool:
"""
Check disk for errors and consistency.
Returns:
bool: True if disk is consistent, False otherwise
"""
def duplicate() -> Disk:
"""
Create a copy of the disk object.
Returns:
Disk: Duplicated disk object
Raises:
CreateException: If duplication fails
"""
def destroy() -> None:
"""
Destroy disk object and free resources.
"""Methods for adding, removing, and modifying partitions.
class Disk:
def addPartition(partition: Partition, constraint: Constraint) -> None:
"""
Add partition to disk using specified constraint.
Args:
partition (Partition): Partition to add
constraint (Constraint): Constraint for partition placement
Raises:
PartitionException: If partition cannot be added
ConstraintException: If constraint cannot be satisfied
"""
def removePartition(partition: Partition) -> None:
"""
Remove partition from disk (but don't delete from device).
Args:
partition (Partition): Partition to remove
Raises:
PartitionException: If partition cannot be removed
"""
def deletePartition(partition: Partition) -> None:
"""
Delete partition from disk and device.
Args:
partition (Partition): Partition to delete
Raises:
PartitionException: If partition cannot be deleted
"""
def deleteAllPartitions() -> None:
"""
Delete all partitions from disk.
Raises:
PartitionException: If partitions cannot be deleted
"""Methods for finding and accessing partitions.
class Disk:
def getFirstPartition() -> Partition:
"""
Get first partition on disk.
Returns:
Partition: First partition or None if no partitions
"""
def getPartitionBySector(sector: int) -> Partition:
"""
Get partition containing the specified sector.
Args:
sector (int): Sector number to check
Returns:
Partition: Partition containing sector or None
"""
def getExtendedPartition() -> Partition:
"""
Get extended partition (for MBR disks).
Returns:
Partition: Extended partition or None if not present
"""
def getPartitionByPath(path: str) -> Partition:
"""
Get partition by device path.
Args:
path (str): Device path (e.g. '/dev/sda1')
Returns:
Partition: Partition with specified path or None
"""Methods for getting partitions by type or property.
class Disk:
def getLogicalPartitions() -> list[Partition]:
"""
Get list of logical partitions (MBR disks).
Returns:
list[Partition]: List of logical partitions
"""
def getPrimaryPartitions() -> list[Partition]:
"""
Get list of primary partitions.
Returns:
list[Partition]: List of primary partitions
"""
def getRaidPartitions() -> list[Partition]:
"""
Get list of partitions with RAID flag set.
Returns:
list[Partition]: List of RAID partitions
"""
def getLVMPartitions() -> list[Partition]:
"""
Get list of partitions with LVM flag set.
Returns:
list[Partition]: List of LVM partitions
"""Methods for finding available free space on the disk.
class Disk:
def getFreeSpaceRegions() -> list[Geometry]:
"""
Get list of Geometry objects representing free space regions.
Returns:
list[Geometry]: List of free space geometries
"""
def getFreeSpacePartitions() -> list[Partition]:
"""
Get list of Partition objects representing free space regions.
Returns:
list[Partition]: List of free space partitions
"""Methods for modifying partition sizes and positions.
class Disk:
def setPartitionGeometry(partition: Partition, constraint: Constraint,
start: int, end: int) -> None:
"""
Set partition geometry within constraint.
Args:
partition (Partition): Partition to modify
constraint (Constraint): Constraint for operation
start (int): New start sector
end (int): New end sector
Raises:
PartitionException: If geometry cannot be set
ConstraintException: If constraint violated
"""
def maximizePartition(partition: Partition, constraint: Constraint) -> None:
"""
Maximize partition size within constraint.
Args:
partition (Partition): Partition to maximize
constraint (Constraint): Constraint for operation
Raises:
PartitionException: If partition cannot be maximized
ConstraintException: If constraint violated
"""
def calculateMaxPartitionGeometry(partition: Partition,
constraint: Constraint = None) -> Geometry:
"""
Get maximum possible geometry for partition.
Args:
partition (Partition): Partition to check
constraint (Constraint, optional): Constraint for operation
Returns:
Geometry: Maximum geometry possible
Raises:
ConstraintException: If no solution exists
"""
def minimizeExtendedPartition() -> None:
"""
Minimize extended partition to fit logical partitions.
Raises:
PartitionException: If operation fails
"""Methods for managing disk-level flags and properties.
class Disk:
def getFlag(flag: int) -> bool:
"""
Get value of disk flag.
Args:
flag (int): Flag constant to check
Returns:
bool: Current flag value
"""
def setFlag(flag: int) -> None:
"""
Set disk flag to True.
Args:
flag (int): Flag constant to set
Raises:
DiskException: If flag cannot be set
"""
def unsetFlag(flag: int) -> None:
"""
Set disk flag to False.
Args:
flag (int): Flag constant to unset
Raises:
DiskException: If flag cannot be unset
"""
def isFlagAvailable(flag: int) -> bool:
"""
Check if flag is available for this disk type.
Args:
flag (int): Flag constant to check
Returns:
bool: True if flag is supported
"""Methods for querying disk type capabilities.
class Disk:
def supportsFeature(feature: int) -> bool:
"""
Check if disk type supports specified feature.
Args:
feature (int): Feature constant to check
Returns:
bool: True if feature is supported
"""import parted
# Read existing partition table
device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
print(f"Disk type: {disk.type}")
print(f"Number of partitions: {len(disk.partitions)}")
print(f"Primary partitions: {disk.primaryPartitionCount}")
# List all partitions
for partition in disk.partitions:
size_mb = partition.getSize('MB')
print(f"Partition {partition.number}: {size_mb:.1f} MB")import parted
# WARNING: This destroys existing data
device = parted.getDevice('/dev/sdb')
# Create new GPT partition table
disk = parted.freshDisk(device, 'gpt')
# Get device constraint for partition operations
constraint = device.getConstraint()
# Create geometry for new partition (example: use first 10GB)
sectors_per_gb = (1024**3) // device.sectorSize
geometry = parted.Geometry(device, start=2048, length=sectors_per_gb * 10)
# Create new partition
partition = parted.Partition(
disk=disk,
type=parted.PARTITION_NORMAL,
geometry=geometry
)
# Add partition to disk
disk.addPartition(partition, constraint)
# Commit changes
disk.commit()import parted
device = parted.getDevice('/dev/sdc')
disk = parted.newDisk(device)
# Find partition to modify
partition = disk.getPartitionByNumber(1)
if partition:
# Get optimal constraint
constraint = device.getOptimalAlignedConstraint()
# Maximize partition size
disk.maximizePartition(partition, constraint)
# Commit changes
disk.commitToDevice()
disk.commitToOS()import parted
device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
# Check disk consistency
if not disk.check():
print("Warning: Disk has consistency issues")
# Display disk capabilities
print(f"Max primary partitions: {disk.maxPrimaryPartitionCount}")
print(f"Supports extended partitions: {disk.supportsFeature(parted.DISK_TYPE_EXTENDED)}")
print(f"Supports partition names: {disk.supportsFeature(parted.DISK_TYPE_PARTITION_NAME)}")
# Check disk flags
if disk.isFlagAvailable(parted.DISK_GPT_PMBR_BOOT):
boot_flag = disk.getFlag(parted.DISK_GPT_PMBR_BOOT)
print(f"GPT PMBR boot flag: {boot_flag}")Common disk label types supported by pyparted:
Use parted.getLabels() to get supported types for current architecture.
Install with Tessl CLI
npx tessl i tessl/pypi-pyparted