CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyparted

Python bindings for GNU parted library providing disk partition management capabilities

Pending
Overview
Eval results
Files

disk-operations.mddocs/

Disk Operations

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.

Capabilities

Disk Creation and Access

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
    """

Disk Class

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 represent

Partition Table Operations

Methods 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.
        """

Partition Management

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
        """

Partition Queries

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
        """

Partition Type Queries

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
        """

Free Space Queries

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
        """

Partition Geometry Operations

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
        """

Disk Flags

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
        """

Disk Type Information

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
        """

Usage Examples

Reading Existing Partition Table

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")

Creating New Partition Table

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()

Partition Table Modifications

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()

Disk Information and Validation

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}")

Disk Types

Common disk label types supported by pyparted:

  • 'gpt' - GUID Partition Table (modern, recommended)
  • 'msdos' - Master Boot Record / DOS partition table
  • 'mac' - Apple partition map
  • 'bsd' - BSD disklabel
  • 'sun' - Sun disk label
  • 'dasd' - S/390 DASD partition table

Use parted.getLabels() to get supported types for current architecture.

Install with Tessl CLI

npx tessl i tessl/pypi-pyparted

docs

constants-reference.md

constraint-solving.md

device-management.md

disk-operations.md

exception-handling.md

filesystem-operations.md

geometry-alignment.md

index.md

partition-management.md

utility-functions.md

tile.json