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

filesystem-operations.mddocs/

Filesystem Operations

Filesystem operations in pyparted provide capabilities for detecting, probing, and managing filesystem types on partitions. These operations help identify existing filesystems and set appropriate filesystem types for partitions.

Capabilities

Filesystem Probing Functions

Functions for detecting and identifying filesystems on storage regions.

def probeFileSystem(geometry: Geometry) -> str:
    """
    Detect filesystem type in the specified geometry region.
    
    Args:
        geometry (Geometry): Region to probe for filesystem
        
    Returns:
        str: Filesystem type name if detected, None if no filesystem found
        
    Raises:
        GeometryException: If geometry is invalid
    """

def probeForSpecificFileSystem(fstype: str, geometry: Geometry) -> Geometry:
    """
    Probe for specific filesystem type and return its exact geometry.
    
    Args:
        fstype (str): Filesystem type to probe for
        geometry (Geometry): Region to search within
        
    Returns:
        Geometry: Exact geometry of filesystem if found
        
    Raises:
        FileSystemException: If filesystem type is invalid
        GeometryException: If geometry is invalid
    """

FileSystem Class

The FileSystem class represents a filesystem with its properties and location.

class FileSystem:
    """
    FileSystem represents a filesystem on a storage device.
    Contains filesystem type and geometry information.
    """
    
    # Read-only properties
    type: str           # Filesystem type name (e.g., 'ext4', 'ntfs', 'fat32')
    geometry: Geometry  # Geometry region containing filesystem
    checked: bool       # Whether filesystem was checked during creation

FileSystem Creation

Constructor for creating filesystem objects.

class FileSystem:
    def __init__(type: str, geometry: Geometry, checked: bool = False) -> FileSystem:
        """
        Create new filesystem object.
        
        Args:
            type (str): Filesystem type name
            geometry (Geometry): Geometry region for filesystem
            checked (bool): Whether filesystem should be marked as checked
            
        Raises:
            FileSystemException: If type is invalid
            GeometryException: If geometry is invalid
        """

Filesystem Types

Access to available filesystem types through the global fileSystemType dictionary.

# Global filesystem type registry
fileSystemType: dict[str, object]  # Maps filesystem names to type objects

Common filesystem types supported by pyparted:

  • Linux Filesystems: ext2, ext3, ext4, xfs, btrfs, reiserfs
  • Windows Filesystems: ntfs, fat16, fat32, exfat
  • Network Filesystems: nfs
  • Other Filesystems: hfs, hfs+, ufs, swap

Usage Examples

Detecting Existing Filesystems

import parted

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

print("Scanning partitions for filesystems:")
for partition in disk.partitions:
    if partition.fileSystem:
        # Filesystem detected during partition table read
        print(f"Partition {partition.number}: {partition.fileSystem.type}")
    else:
        # Probe for filesystem manually
        try:
            fs_type = parted.probeFileSystem(partition.geometry)
            if fs_type:
                print(f"Partition {partition.number}: {fs_type} (probed)")
            else:
                print(f"Partition {partition.number}: No filesystem detected")
        except Exception as e:
            print(f"Partition {partition.number}: Error probing - {e}")

Probing Specific Filesystem Types

import parted

device = parted.getDevice('/dev/sdb')
partition_geometry = parted.Geometry(device, start=2048, length=2097152)  # 1GB

# Probe for specific filesystems
filesystem_types = ['ext4', 'ntfs', 'fat32', 'xfs']

for fs_type in filesystem_types:
    try:
        detected_geometry = parted.probeForSpecificFileSystem(fs_type, partition_geometry)
        if detected_geometry:
            print(f"Found {fs_type} filesystem:")
            print(f"  Start: {detected_geometry.start}")
            print(f"  Length: {detected_geometry.length}")
            print(f"  End: {detected_geometry.end}")
            break
    except parted.FileSystemException:
        continue  # Filesystem type not found
    except Exception as e:
        print(f"Error probing for {fs_type}: {e}")
else:
    print("No recognized filesystem found")

Creating FileSystem Objects

import parted

device = parted.getDevice('/dev/sdc')

# Create geometry for filesystem
fs_geometry = parted.Geometry(device, start=2048, length=4194304)  # 2GB

# Create filesystem objects for different types
ext4_fs = parted.FileSystem('ext4', fs_geometry, checked=True)
ntfs_fs = parted.FileSystem('ntfs', fs_geometry, checked=False)

print(f"ext4 filesystem: type={ext4_fs.type}, checked={ext4_fs.checked}")
print(f"ntfs filesystem: type={ntfs_fs.type}, checked={ntfs_fs.checked}")

# Use filesystem with partition
disk = parted.newDisk(device)
partition = parted.Partition(
    disk=disk,
    type=parted.PARTITION_NORMAL,
    geometry=fs_geometry,
    fs=ext4_fs
)

print(f"Partition filesystem: {partition.fileSystem.type}")

Setting Partition Filesystem Types

import parted

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

# Find partition to modify
partition = disk.getPartitionByNumber(1)
if partition:
    # Create filesystem object for desired type
    new_geometry = partition.geometry
    new_filesystem = parted.FileSystem('ext4', new_geometry)
    
    # Set filesystem type on partition
    partition.setSystem(new_filesystem)
    
    # Commit changes
    disk.commit()
    
    print(f"Set partition {partition.number} filesystem type to ext4")
else:
    print("Partition not found")

Comprehensive Filesystem Detection

import parted

def detect_all_filesystems(device_path):
    """Detect all filesystems on a device."""
    device = parted.getDevice(device_path)
    disk = parted.newDisk(device)
    
    results = []
    
    for partition in disk.partitions:
        partition_info = {
            'number': partition.number,
            'path': partition.path,
            'size_gb': partition.getSize('GB'),
            'filesystem': None
        }
        
        # First check if filesystem is already detected
        if partition.fileSystem:
            partition_info['filesystem'] = partition.fileSystem.type
        else:
            # Probe for filesystem
            try:
                fs_type = parted.probeFileSystem(partition.geometry)
                partition_info['filesystem'] = fs_type or 'Unknown'
            except Exception as e:
                partition_info['filesystem'] = f'Error: {e}'
        
        results.append(partition_info)
    
    return results

# Use the function
device_path = '/dev/sda'
filesystems = detect_all_filesystems(device_path)

print(f"Filesystems on {device_path}:")
for info in filesystems:
    print(f"  {info['path']}: {info['filesystem']} ({info['size_gb']:.1f} GB)")

Filesystem Type Validation

import parted

# Check available filesystem types
print("Available filesystem types:")
for fs_name in sorted(parted.fileSystemType.keys()):
    print(f"  {fs_name}")

# Validate filesystem type before use
def is_valid_filesystem_type(fs_type):
    return fs_type in parted.fileSystemType

# Test filesystem types
test_types = ['ext4', 'ntfs', 'invalid_type', 'fat32']
for fs_type in test_types:
    valid = is_valid_filesystem_type(fs_type)
    print(f"{fs_type}: {'Valid' if valid else 'Invalid'}")

Partition Creation with Filesystem

import parted

device = parted.getDevice('/dev/sdd')

# Create fresh partition table
disk = parted.freshDisk(device, 'gpt')

# Create constraint for operations
constraint = device.getOptimalAlignedConstraint()

# Create geometry for new partition
start_sector = 2048
size_sectors = (50 * 1024**3) // device.sectorSize  # 50GB
geometry = parted.Geometry(device, start=start_sector, length=size_sectors)

# Create filesystem object
filesystem = parted.FileSystem('ext4', geometry)

# Create partition with filesystem
partition = parted.Partition(
    disk=disk,
    type=parted.PARTITION_NORMAL,
    geometry=geometry,
    fs=filesystem
)

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

print(f"Created partition with ext4 filesystem at {partition.path}")

Error Handling in Filesystem Operations

import parted

def safe_filesystem_probe(geometry):
    """Safely probe for filesystem with error handling."""
    try:
        fs_type = parted.probeFileSystem(geometry)
        return fs_type if fs_type else "No filesystem"
    except parted.FileSystemException as e:
        return f"Filesystem error: {e}"
    except parted.GeometryException as e:
        return f"Geometry error: {e}"
    except Exception as e:
        return f"Unknown error: {e}"

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

for partition in disk.partitions:
    result = safe_filesystem_probe(partition.geometry)
    print(f"Partition {partition.number}: {result}")

Filesystem Detection Limitations

Important Notes

  1. Read-Only Detection: pyparted can detect existing filesystems but cannot create or format them
  2. Type Setting Only: setSystem() only sets the partition's filesystem type hint, it doesn't format
  3. Probe Accuracy: Filesystem probing may not detect all filesystem types or corrupted filesystems
  4. No Filesystem Operations: pyparted doesn't provide filesystem resize, check, or repair operations

External Tools Integration

For actual filesystem operations, use external tools:

import subprocess
import parted

def format_partition(partition_path, fs_type):
    """Format partition using external tools (example - be careful!)."""
    format_commands = {
        'ext4': ['mkfs.ext4', '-F', partition_path],
        'ntfs': ['mkfs.ntfs', '-f', partition_path],
        'fat32': ['mkfs.vfat', '-F32', partition_path],
        'xfs': ['mkfs.xfs', '-f', partition_path]
    }
    
    if fs_type in format_commands:
        try:
            subprocess.run(format_commands[fs_type], check=True)
            print(f"Formatted {partition_path} as {fs_type}")
        except subprocess.CalledProcessError as e:
            print(f"Format failed: {e}")
    else:
        print(f"Unsupported filesystem type: {fs_type}")

# WARNING: This destroys data! Use with extreme caution.
# format_partition('/dev/sdb1', 'ext4')

Filesystem Types Reference

Linux Filesystems

  • ext2, ext3, ext4: Extended filesystems (ext4 recommended)
  • xfs: High-performance journaling filesystem
  • btrfs: B-tree filesystem with advanced features
  • reiserfs: Journaling filesystem (deprecated)

Windows Filesystems

  • ntfs: Windows NT filesystem
  • fat16, fat32: File Allocation Table filesystems
  • exfat: Extended File Allocation Table

Special Filesystems

  • swap: Linux swap space
  • linux-swap: Linux swap partition
  • hfs, hfs+: Apple Hierarchical File System

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