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

partition-management.mddocs/

Partition Management

Partition management in pyparted provides detailed control over individual partitions including creation, modification, flag management, and filesystem type handling.

Capabilities

Partition Class

The Partition class represents an individual partition within a disk's partition table.

class Partition:
    """
    Partition represents an individual partition on a disk.
    Provides access to partition properties and operations.
    """
    
    # Read-only properties
    disk: Disk          # Parent disk object
    geometry: Geometry  # Partition geometry (position and size)
    fileSystem: FileSystem  # Associated filesystem object
    number: int         # Partition number
    path: str          # Device path (e.g. '/dev/sda1')
    type: int          # Partition type constant
    name: str          # Partition name (if supported)
    active: bool       # Whether partition is active/bootable
    busy: bool         # Whether partition is in use by system

Partition Creation

Constructor for creating new partition objects.

class Partition:
    def __init__(disk: Disk, type: int, geometry: Geometry, 
                 fs: FileSystem = None) -> Partition:
        """
        Create new partition object.
        
        Args:
            disk (Disk): Parent disk object
            type (int): Partition type constant
            geometry (Geometry): Partition geometry
            fs (FileSystem, optional): Filesystem type
            
        Raises:
            PartitionException: If partition cannot be created
        """

Navigation Methods

Methods for traversing partitions within a disk.

class Partition:
    def nextPartition(start: Partition = None) -> Partition:
        """
        Get next partition on disk after this one.
        
        Args:
            start (Partition, optional): Starting partition for search
            
        Returns:
            Partition: Next partition or None if at end
        """

Partition Properties

Methods for accessing and modifying partition properties.

class Partition:
    def setName(name: str) -> None:
        """
        Set partition name (on labels that support names).
        
        Args:
            name (str): Name to set for partition
            
        Raises:
            PartitionException: If name cannot be set
        """
    
    def getName() -> str:
        """
        Get partition name (on labels that support names).
        
        Returns:
            str: Partition name or None if not supported/set
        """
    
    def resetNumber() -> None:
        """
        Reset partition number (for renumbering operations).
        
        Raises:
            PartitionException: If number cannot be reset
        """
    
    def getSize(unit: str = 'MB') -> float:
        """
        Get partition size in specified unit (deprecated, use getLength).
        
        Args:
            unit (str): Unit for size ('b', 'kb', 'mb', 'gb', 'tb')
            
        Returns:
            float: Partition size in specified unit
            
        Raises:
            SyntaxError: If unit is invalid
            
        Note:
            This method is deprecated. Use getLength() instead.
        """
    
    def getLength(unit: str = "sectors") -> float:
        """
        Get partition length in sectors or bytes with SI/IEC prefixes.
        
        Args:
            unit (str): Unit ('sectors', 'B', 'kB', 'MB', 'GB', 'TB', 'KiB', 'MiB', 'GiB', 'TiB')
            
        Returns:
            float: Partition length in specified unit
        """

Partition Flags

Methods for managing partition flags (boot, hidden, etc.).

class Partition:
    def getFlag(flag: int) -> bool:
        """
        Get current value of partition flag.
        
        Args:
            flag (int): Flag constant to check
            
        Returns:
            bool: Current flag value
        """
    
    def setFlag(flag: int) -> None:
        """
        Set partition flag to True.
        
        Args:
            flag (int): Flag constant to set
            
        Raises:
            PartitionException: If flag cannot be set
        """
    
    def unsetFlag(flag: int) -> None:
        """
        Set partition flag to False.
        
        Args:
            flag (int): Flag constant to unset
            
        Raises:
            PartitionException: If flag cannot be unset
        """
    
    def isFlagAvailable(flag: int) -> bool:
        """
        Check if flag is supported for this partition.
        
        Args:
            flag (int): Flag constant to check
            
        Returns:
            bool: True if flag is supported
        """

Type ID and UUID Methods

Methods for managing partition type identifiers (GPT/modern partition tables).

class Partition:
    def getTypeId() -> int:
        """
        Get partition type ID as integer (requires parted > 3.5).
        
        Returns:
            int: Partition type ID or None if not supported
            
        Raises:
            NotImplementedError: If parted version < 3.5
            PartitionException: If type ID cannot be retrieved
        """
    
    def setTypeId(id: int) -> None:
        """
        Set partition type ID as integer (requires parted > 3.5).
        
        Args:
            id (int): Type ID to set
            
        Raises:
            NotImplementedError: If parted version < 3.5
            PartitionException: If type ID cannot be set
        """
    
    def getTypeUuid() -> bytes:
        """
        Get partition type UUID as 16 bytes (requires parted > 3.5).
        
        Returns:
            bytes: Partition type UUID or None if not supported
            
        Raises:
            NotImplementedError: If parted version < 3.5
            PartitionException: If type UUID cannot be retrieved
        """
    
    def setTypeUuid(uuid: bytes) -> None:
        """
        Set partition type UUID as 16 bytes (requires parted > 3.5).
        
        Args:
            uuid (bytes): Type UUID to set (16 bytes)
            
        Raises:
            NotImplementedError: If parted version < 3.5
            PartitionException: If type UUID cannot be set
        """
    
    # Properties for type identifiers
    type_id: int    # Partition type ID (read/write property)
    type_uuid: bytes # Partition type UUID (read/write property)

Filesystem and System Type

Methods for managing partition filesystem type and system type.

class Partition:
    def setSystem(fs: FileSystem) -> None:
        """
        Set filesystem type for partition.
        
        Args:
            fs (FileSystem): Filesystem object to set
            
        Raises:
            PartitionException: If filesystem type cannot be set
        """

Partition Names

Methods for partition name management (supported on GPT and some other formats).

class Partition:
    def getName() -> str:
        """
        Get partition name.
        
        Returns:
            str: Partition name
            
        Raises:
            PartitionException: If names not supported or error occurs
        """
    
    def setName(name: str) -> None:
        """
        Set partition name.
        
        Args:
            name (str): New partition name
            
        Raises:
            PartitionException: If names not supported or name invalid
        """

Advanced Partition Methods

Additional methods for partition manipulation and information.

class Partition:
    def nextPartition() -> Partition:
        """
        Get next partition on disk after this one.
        
        Returns:
            Partition: Next partition or None if at end
        """
    
    def getMaxGeometry(constraint: Constraint) -> Geometry:
        """
        Get maximum geometry this partition can be grown to.
        
        Args:
            constraint (Constraint): Constraint for growth operation
            
        Returns:
            Geometry: Maximum possible geometry
            
        Raises:
            PartitionException: If geometry cannot be calculated
        """
    
    def getMaxAvailableSize(unit: str = "MB") -> float:
        """
        Get maximum size this partition can grow to including adjacent free space.
        
        Args:
            unit (str): Unit for size ('b', 'kb', 'mb', 'gb', 'tb')
            
        Returns:
            float: Maximum available size in specified unit
            
        Raises:
            SyntaxError: If unit is invalid
        """
    
    def getFlagsAsString() -> str:
        """
        Get comma-separated string of active partition flags.
        
        Returns:
            str: String representation of active flags
        """
    
    def getDeviceNodeName() -> str:
        """
        Get device node name without '/dev/' prefix.
        
        Returns:
            str: Device node name (e.g. 'sda1')
        """

Usage Examples

Creating New Partitions

import parted

# Get device and create/read disk
device = parted.getDevice('/dev/sdb')
disk = parted.newDisk(device)  # or freshDisk for new partition table

# Get constraint for partition operations
constraint = device.getOptimalAlignedConstraint()

# Define partition geometry (example: 10GB starting at sector 2048)
start_sector = 2048
size_sectors = (10 * 1024**3) // device.sectorSize  # 10GB in sectors
geometry = parted.Geometry(device, start=start_sector, length=size_sectors)

# Create primary partition
partition = parted.Partition(
    disk=disk,
    type=parted.PARTITION_NORMAL,
    geometry=geometry
)

# Add to disk and commit
disk.addPartition(partition, constraint)
disk.commit()

print(f"Created partition {partition.number} at {partition.path}")

Managing Partition Flags

import parted

device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
partition = disk.getPartitionByNumber(1)

if partition:
    # Check available flags
    available_flags = []
    for flag_name, flag_value in parted.partitionFlag.items():
        if partition.isFlagAvailable(flag_value):
            available_flags.append(flag_name)
    
    print(f"Available flags: {available_flags}")
    
    # Set boot flag
    if partition.isFlagAvailable(parted.PARTITION_BOOT):
        partition.setFlag(parted.PARTITION_BOOT, True)
        disk.commit()
        print("Boot flag set")
    
    # Check current flags
    boot = partition.getFlag(parted.PARTITION_BOOT)
    hidden = partition.getFlag(parted.PARTITION_HIDDEN)
    print(f"Boot: {boot}, Hidden: {hidden}")

Partition Information

import parted

device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)

# Display information for all partitions
for partition in disk.partitions:
    print(f"\nPartition {partition.number}:")
    print(f"  Path: {partition.path}")
    print(f"  Type: {partition.type}")
    print(f"  Size: {partition.getSize('GB'):.2f} GB")
    print(f"  Start: {partition.geometry.start}")
    print(f"  End: {partition.geometry.end}")
    print(f"  Active: {partition.active}")
    print(f"  Busy: {partition.isBusy()}")
    
    # Show filesystem if detected
    if partition.fileSystem:
        print(f"  Filesystem: {partition.fileSystem.type}")
    
    # Show name if supported and set
    try:
        name = partition.getName()
        if name:
            print(f"  Name: {name}")
    except parted.PartitionException:
        pass  # Names not supported on this disk type

Partition Resizing

import parted

device = parted.getDevice('/dev/sdb')
disk = parted.newDisk(device)
partition = disk.getPartitionByNumber(1)

if partition and not partition.isBusy():
    # Get constraint for operations
    constraint = device.getOptimalAlignedConstraint()
    
    # Maximize partition size
    disk.maximizePartition(partition, constraint)
    
    # Or set specific geometry
    new_end = partition.geometry.start + (20 * 1024**3) // device.sectorSize
    disk.setPartitionGeometry(
        partition, 
        constraint, 
        partition.geometry.start, 
        new_end
    )
    
    disk.commit()
    print(f"Partition resized to {partition.getSize('GB'):.2f} GB")
else:
    print("Partition is busy or not found")

Working with Extended Partitions

import parted

device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)

# Find extended partition (MBR only)
extended = disk.getExtendedPartition()
if extended:
    print(f"Extended partition: {extended.number}")
    
    # List logical partitions
    logical_partitions = []
    for partition in disk.partitions:
        if partition.type == parted.PARTITION_LOGICAL:
            logical_partitions.append(partition)
    
    print(f"Logical partitions: {len(logical_partitions)}")
    for partition in logical_partitions:
        print(f"  {partition.number}: {partition.getSize('GB'):.1f} GB")

Partition Names (GPT)

import parted

device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)

# Only works with disk types that support names (like GPT)
if disk.supportsFeature(parted.DISK_TYPE_PARTITION_NAME):
    partition = disk.getPartitionByNumber(1)
    if partition:
        try:
            # Set partition name
            partition.setName("System Boot")
            disk.commit()
            
            # Read name back
            name = partition.getName()
            print(f"Partition name: {name}")
        except parted.PartitionException as e:
            print(f"Name operation failed: {e}")
else:
    print("Disk type does not support partition names")

Partition Types

Partition type constants define the role and behavior of partitions:

Basic Types

  • PARTITION_NORMAL - Regular primary partition
  • PARTITION_LOGICAL - Logical partition (within extended)
  • PARTITION_EXTENDED - Extended partition container

Special Types

  • PARTITION_FREESPACE - Free space region
  • PARTITION_METADATA - Metadata partition
  • PARTITION_PROTECTED - Protected/system partition

Partition Flags

Common partition flags available (support varies by disk type):

System Flags

  • PARTITION_BOOT - Boot/active flag
  • PARTITION_ROOT - Root filesystem flag
  • PARTITION_SWAP - Swap partition flag
  • PARTITION_HIDDEN - Hidden partition flag

Special Purpose Flags

  • PARTITION_RAID - Software RAID member
  • PARTITION_LVM - LVM physical volume
  • PARTITION_LBA - LBA addressing required
  • PARTITION_PREP - PowerPC PReP boot partition
  • PARTITION_ESP - EFI System Partition
  • PARTITION_BIOS_GRUB - BIOS boot partition for GRUB

Microsoft Flags

  • PARTITION_MSFT_RESERVED - Microsoft Reserved partition
  • PARTITION_MSFT_DATA - Microsoft Basic Data partition

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