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

device-management.mddocs/

Device Management

Device management in pyparted provides access to physical storage devices and their properties. Devices represent the hardware-level interface to disks, SSDs, and other storage media.

Capabilities

Device Discovery

Functions for discovering and accessing storage devices in the system.

def getDevice(path: str) -> Device:
    """
    Get a Device object for the specified device path.
    
    Args:
        path (str): Operating system path to device node (e.g. '/dev/sda')
    
    Returns:
        Device: Device object for the specified path
        
    Raises:
        DeviceException: If invalid path is provided
    """

def getAllDevices() -> list[Device]:
    """
    Return a list of Device objects for all devices in the system.
    
    Returns:
        list[Device]: List of all detected devices
    """

def freeAllDevices() -> None:
    """
    Free all Device objects. Generally not needed in normal usage.
    """

Device Class

The Device class represents a physical storage device with comprehensive properties and methods.

class Device:
    """
    Device represents a physical piece of hardware in the system.
    Provides low-level, operating system specific interface to hardware.
    """
    
    # Read-only properties
    model: str  # Model name and vendor of device
    path: str   # Filesystem node path (e.g. '/dev/sda')
    type: int   # Device type constant (DEVICE_SCSI, DEVICE_IDE, etc.)
    sectorSize: int          # Logical sector size in bytes
    physicalSectorSize: int  # Physical sector size in bytes
    length: int              # Device size in sectors
    openCount: int           # Number of times device has been opened
    readOnly: bool           # Read-only status
    externalMode: bool       # External mode status
    dirty: bool              # Dirty status
    bootDirty: bool          # Boot sector dirty status
    host: int                # SCSI host ID
    did: int                 # SCSI device ID
    busy: bool               # Whether device is in use
    hardwareGeometry: tuple  # Hardware CHS geometry (cylinders, heads, sectors)
    biosGeometry: tuple      # BIOS CHS geometry (cylinders, heads, sectors)
    minimumAlignment: Alignment  # Minimum alignment for this device
    optimumAlignment: Alignment  # Optimum alignment for this device

Device Operations

Methods for device I/O and management operations.

class Device:
    def open() -> None:
        """
        Open device for I/O operations.
        
        Raises:
            IOException: If device cannot be opened
        """
    
    def close() -> None:
        """
        Close device after I/O operations.
        
        Raises:
            IOException: If device cannot be closed
        """
    
    def clobber() -> None:
        """
        Remove existing disk label from device.
        WARNING: This destroys the partition table.
        
        Raises:
            IOException: If operation fails
        """
    
    def removeFromCache() -> None:
        """
        Remove device from internal cache.
        """
    
    def destroy() -> None:
        """
        Destroy device object and free resources.
        """
    
    def beginExternalAccess() -> None:
        """
        Set up device for use by external program.
        Call before running external programs on device.
        
        Raises:
            IOException: If external access cannot be enabled
        """
    
    def endExternalAccess() -> None:
        """
        Turn off external access mode for device.
        Call after external program finishes using device.
        
        Raises:
            IOException: If external access cannot be disabled  
        """

Device I/O Operations

Low-level read/write operations on devices.

class Device:
    def read(start: int, count: int) -> bytes:
        """
        Read sectors from device.
        
        Args:
            start (int): Starting sector number
            count (int): Number of sectors to read
            
        Returns:
            bytes: Data read from device
            
        Raises:
            IOException: If read operation fails
        """
    
    def write(buffer: bytes, start: int, count: int) -> None:
        """
        Write sectors to device.
        
        Args:
            buffer (bytes): Data to write
            start (int): Starting sector number  
            count (int): Number of sectors to write
            
        Raises:
            IOException: If write operation fails
        """
    
    def sync(fast: bool = False) -> None:
        """
        Synchronize device, ensuring all writes are committed.
        
        Args:
            fast (bool): If True, perform fast sync; if False, full sync
        
        Raises:
            IOException: If sync operation fails
        """
    
    def check(start: int, count: int) -> bool:
        """
        Check device sectors for errors.
        
        Args:
            start (int): Starting sector number
            count (int): Number of sectors to check
            
        Returns:
            bool: True if sectors are healthy, False otherwise
            
        Raises:
            IOException: If check operation fails
        """

Size and Conversion Methods

Methods for getting device size and converting between units.

class Device:
    def getSize(unit: str = "MB") -> float:
        """
        Get device size in specified unit (deprecated, use getLength).
        
        Args:
            unit (str): Unit string ('b', 'kb', 'mb', 'gb', 'tb')
            
        Returns:
            float: Device size in specified unit
            
        Raises:
            SyntaxError: If invalid unit specified
            
        Note:
            This method is deprecated. Use getLength() instead.
        """
    
    def getLength(unit: str = "sectors") -> float:
        """
        Get device 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: Device length in specified unit
        """

Sector/Cylinder Conversion Methods

Methods for converting between sector and cylinder addressing.

class Device:
    def startSectorToCylinder(sector: int) -> int:
        """
        Convert start sector number to cylinder number.
        
        Args:
            sector (int): Sector number
            
        Returns:
            int: Cylinder number
        """
    
    def endSectorToCylinder(sector: int) -> int:
        """
        Convert end sector number to cylinder number.
        
        Args:
            sector (int): Sector number
            
        Returns:
            int: Cylinder number
        """
    
    def startCylinderToSector(cylinder: int) -> int:
        """
        Convert cylinder number to start sector number.
        
        Args:
            cylinder (int): Cylinder number
            
        Returns:
            int: Start sector number
        """
    
    def endCylinderToSector(cylinder: int) -> int:
        """
        Convert cylinder number to end sector number.
        
        Args:
            cylinder (int): Cylinder number
            
        Returns:
            int: End sector number
        """

Constraint and Alignment

Methods and properties for obtaining device-specific constraint and alignment information.

class Device:
    def getConstraint() -> Constraint:
        """
        Get constraint that accepts any region on this device.
        
        Returns:
            Constraint: Device constraint object
            
        Raises:
            CreateException: If constraint creation fails
        """
    
    def getMinimumAlignment() -> Alignment:
        """
        Get minimum alignment required by device.
        
        Returns:
            Alignment: Minimum alignment object
        """
    
    def getOptimumAlignment() -> Alignment:
        """
        Get optimum alignment for best device performance.
        
        Returns:
            Alignment: Optimum alignment object
        """
    
    # Properties for alignment constraints  
    minimalAlignedConstraint: Constraint  # Constraint with minimal alignment requirements
    optimalAlignedConstraint: Constraint  # Constraint with optimal alignment requirements

Usage Examples

Basic Device Information

import parted

# Get device information
device = parted.getDevice('/dev/sda')
print(f"Model: {device.model}")
print(f"Size: {device.length * device.sectorSize / (1024**3):.1f} GB")
print(f"Sector size: {device.sectorSize} bytes")
print(f"Physical sector size: {device.physicalSectorSize} bytes")
print(f"Read-only: {device.readOnly}")
print(f"Busy: {device.busy}")

List All Devices

import parted

# List all storage devices
for device in parted.getAllDevices():
    size_gb = device.length * device.sectorSize / (1024**3)
    print(f"{device.path}: {device.model} ({size_gb:.1f} GB)")

Safe Device Operations

import parted

try:
    device = parted.getDevice('/dev/sdb')
    
    # Check if device is safe to modify
    if device.busy:
        print("Device is busy, cannot modify")
        return
    
    if device.readOnly:
        print("Device is read-only, cannot modify")
        return
    
    # Perform operations
    device.open()
    try:
        # ... perform I/O operations
        device.sync()
    finally:
        device.close()
        
except parted.DeviceException as e:
    print(f"Device error: {e}")
except parted.IOException as e:
    print(f"I/O error: {e}")

Device Types

Device type constants identify different storage device interfaces:

  • DEVICE_SCSI - SCSI devices
  • DEVICE_IDE - IDE/PATA devices
  • DEVICE_NVME - NVMe devices
  • DEVICE_VIRTBLK - Virtual block devices
  • DEVICE_DM - Device mapper devices
  • DEVICE_FILE - File-based devices
  • DEVICE_UNKNOWN - Unknown device types

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