Python bindings for GNU parted library providing disk partition management capabilities
—
Geometry and alignment in pyparted provide precise control over partition positioning and alignment constraints. These classes are essential for ensuring partitions are properly positioned for optimal performance and compatibility.
The Geometry class represents a contiguous region of sectors on a storage device.
class Geometry:
"""
Geometry represents a region on a device expressed as starting sector and length.
Used throughout pyparted for defining partition boundaries and operations.
"""
# Properties
device: Device # Associated device object
start: int # Starting sector number
end: int # Ending sector number (inclusive)
length: int # Length in sectorsConstructor and creation methods for geometry objects.
class Geometry:
def __init__(device: Device, start: int = None, length: int = None,
end: int = None) -> Geometry:
"""
Create new geometry object.
Args:
device (Device): Device object
start (int): Starting sector
length (int): Length in sectors (alternative to end)
end (int): Ending sector (alternative to length)
Raises:
GeometryException: If parameters are invalid
"""
def duplicate() -> Geometry:
"""
Create a copy of this geometry.
Returns:
Geometry: Duplicated geometry object
Raises:
CreateException: If duplication fails
"""Methods for geometry manipulation and calculations.
class Geometry:
def intersect(geometry: Geometry) -> Geometry:
"""
Create geometry representing intersection with another geometry.
Args:
geometry (Geometry): Geometry to intersect with
Returns:
Geometry: Intersection geometry or None if no overlap
Raises:
CreateException: If intersection calculation fails
"""
def overlapsWith(geometry: Geometry) -> bool:
"""
Check if this geometry overlaps with another.
Args:
geometry (Geometry): Geometry to check against
Returns:
bool: True if geometries overlap
"""
def contains(geometry: Geometry) -> bool:
"""
Check if this geometry completely contains another.
Args:
geometry (Geometry): Geometry to check
Returns:
bool: True if this geometry contains the other
"""
def containsSector(sector: int) -> bool:
"""
Check if this geometry contains the specified sector.
Args:
sector (int): Sector number to check
Returns:
bool: True if sector is within this geometry
"""
def equal(geometry: Geometry) -> bool:
"""
Check if this geometry is equal to another.
Args:
geometry (Geometry): Geometry to compare
Returns:
bool: True if geometries are equal
"""Methods for modifying geometry parameters.
class Geometry:
def set(start: int, length: int) -> None:
"""
Set geometry start and length.
Args:
start (int): New starting sector
length (int): New length in sectors
Raises:
GeometryException: If parameters are invalid
"""
def setStart(start: int) -> None:
"""
Set geometry starting sector.
Args:
start (int): New starting sector
Raises:
GeometryException: If start is invalid
"""
def setEnd(end: int) -> None:
"""
Set geometry ending sector.
Args:
end (int): New ending sector
Raises:
GeometryException: If end is invalid
"""Methods for reading and writing to geometry regions.
class Geometry:
def read(offset: int, count: int) -> bytes:
"""
Read data from geometry region.
Args:
offset (int): Offset in sectors from geometry start
count (int): Number of sectors to read
Returns:
bytes: Data read from geometry
Raises:
IOException: If read operation fails
"""
def write(buffer: bytes, offset: int, count: int) -> None:
"""
Write data to geometry region.
Args:
buffer (bytes): Data to write
offset (int): Offset in sectors from geometry start
count (int): Number of sectors to write
Raises:
IOException: If write operation fails
"""
def sync() -> None:
"""
Synchronize geometry region.
Raises:
IOException: If sync operation fails
"""
def syncFast() -> None:
"""
Fast synchronization of geometry region.
Raises:
IOException: If sync operation fails
"""
def check(offset: int, granularity: int, count: int,
timer: object = None) -> bool:
"""
Check geometry region for errors.
Args:
offset (int): Offset in sectors from geometry start
granularity (int): Granularity for checking
count (int): Number of sectors to check
timer (object, optional): Timer object for progress
Returns:
bool: True if region is healthy
Raises:
IOException: If check operation fails
"""
def map(dst_geometry: Geometry, sector: int) -> int:
"""
Map sector from this geometry to destination geometry.
Args:
dst_geometry (Geometry): Destination geometry
sector (int): Sector to map
Returns:
int: Mapped sector in destination geometry
Raises:
GeometryException: If mapping fails
"""The Alignment class describes constraints on sector alignment.
class Alignment:
"""
Alignment describes constraints on how sectors and geometries are aligned.
Used to ensure partitions start and end at optimal sector boundaries.
"""
# Properties
offset: int # Alignment offset
grainSize: int # Alignment grain size (alignment multiple)Constructor for creating alignment objects.
class Alignment:
def __init__(offset: int, grainSize: int) -> Alignment:
"""
Create new alignment object.
Args:
offset (int): Alignment offset
grainSize (int): Alignment grain size
Raises:
AlignmentException: If parameters are invalid
"""Methods for alignment calculations and operations.
class Alignment:
def intersect(alignment: Alignment) -> Alignment:
"""
Create alignment representing intersection with another alignment.
Args:
alignment (Alignment): Alignment to intersect with
Returns:
Alignment: Intersection alignment
Raises:
ArithmeticError: If intersection calculation fails
"""
def alignUp(geometry: Geometry, sector: int) -> int:
"""
Align sector upward to next aligned position.
Args:
geometry (Geometry): Geometry context for alignment
sector (int): Sector to align
Returns:
int: Next aligned sector >= input sector
Raises:
ArithmeticError: If alignment calculation fails
"""
def alignDown(geometry: Geometry, sector: int) -> int:
"""
Align sector downward to previous aligned position.
Args:
geometry (Geometry): Geometry context for alignment
sector (int): Sector to align
Returns:
int: Previous aligned sector <= input sector
Raises:
ArithmeticError: If alignment calculation fails
"""
def alignNearest(geometry: Geometry, sector: int) -> int:
"""
Align sector to nearest aligned position.
Args:
geometry (Geometry): Geometry context for alignment
sector (int): Sector to align
Returns:
int: Nearest aligned sector
Raises:
ArithmeticError: If alignment calculation fails
"""
def isAligned(geometry: Geometry, sector: int) -> bool:
"""
Check if sector is properly aligned.
Args:
geometry (Geometry): Geometry context for alignment
sector (int): Sector to check
Returns:
bool: True if sector is aligned
"""import parted
device = parted.getDevice('/dev/sda')
# Create geometry for first 1GB of device
sectors_per_gb = (1024**3) // device.sectorSize
geometry1 = parted.Geometry(device, start=0, length=sectors_per_gb)
# Create geometry for second 1GB
geometry2 = parted.Geometry(device, start=sectors_per_gb, length=sectors_per_gb)
print(f"Geometry 1: sectors {geometry1.start} to {geometry1.end}")
print(f"Geometry 2: sectors {geometry2.start} to {geometry2.end}")
# Check for overlap
if geometry1.overlapsWith(geometry2):
print("Geometries overlap")
else:
print("Geometries don't overlap")
# Check if geometry contains specific sector
if geometry1.containsSector(500000):
print("Geometry 1 contains sector 500000")import parted
device = parted.getDevice('/dev/sda')
# Create overlapping geometries
geom1 = parted.Geometry(device, start=1000, length=2000) # sectors 1000-2999
geom2 = parted.Geometry(device, start=2000, length=2000) # sectors 2000-3999
# Find intersection
intersection = geom1.intersect(geom2)
if intersection:
print(f"Intersection: sectors {intersection.start} to {intersection.end}")
print(f"Intersection length: {intersection.length} sectors")
else:
print("No intersection")import parted
device = parted.getDevice('/dev/sda')
# Get device optimal alignment
optimal_alignment = device.getOptimumAlignment()
print(f"Optimal alignment - offset: {optimal_alignment.offset}, grain: {optimal_alignment.grainSize}")
# Create geometry for alignment operations
geometry = parted.Geometry(device, start=0, length=device.length)
# Align a sector value
unaligned_sector = 1000
aligned_up = optimal_alignment.alignUp(geometry, unaligned_sector)
aligned_down = optimal_alignment.alignDown(geometry, unaligned_sector)
aligned_nearest = optimal_alignment.alignNearest(geometry, unaligned_sector)
print(f"Original sector: {unaligned_sector}")
print(f"Aligned up: {aligned_up}")
print(f"Aligned down: {aligned_down}")
print(f"Aligned nearest: {aligned_nearest}")
# Check if sector is aligned
is_aligned = optimal_alignment.isAligned(geometry, aligned_up)
print(f"Aligned up sector is properly aligned: {is_aligned}")import parted
device = parted.getDevice('/dev/sdb')
disk = parted.newDisk(device)
# Get optimal alignment for performance
alignment = device.getOptimumAlignment()
# Create geometry for entire device
device_geometry = parted.Geometry(device, start=0, length=device.length)
# Calculate aligned start for new partition
# Start after any existing partitions, aligned optimally
desired_start = 2048 # Common starting point
aligned_start = alignment.alignUp(device_geometry, desired_start)
# Calculate size (10GB) and align the end
size_sectors = (10 * 1024**3) // device.sectorSize
desired_end = aligned_start + size_sectors - 1
aligned_end = alignment.alignDown(device_geometry, desired_end)
# Create aligned geometry
aligned_geometry = parted.Geometry(
device,
start=aligned_start,
end=aligned_end
)
print(f"Aligned partition: sectors {aligned_start} to {aligned_end}")
print(f"Size: {aligned_geometry.length * device.sectorSize / (1024**3):.2f} GB")
# Create partition with aligned geometry
partition = parted.Partition(
disk=disk,
type=parted.PARTITION_NORMAL,
geometry=aligned_geometry
)
# Use constraint for adding partition
constraint = device.getOptimalAlignedConstraint()
disk.addPartition(partition, constraint)
disk.commit()import parted
device = parted.getDevice('/dev/sda')
# Get different alignment requirements
min_alignment = device.getMinimumAlignment()
opt_alignment = device.getOptimumAlignment()
# Create intersection of alignments
combined_alignment = min_alignment.intersect(opt_alignment)
print(f"Minimum alignment: offset={min_alignment.offset}, grain={min_alignment.grainSize}")
print(f"Optimal alignment: offset={opt_alignment.offset}, grain={opt_alignment.grainSize}")
print(f"Combined alignment: offset={combined_alignment.offset}, grain={combined_alignment.grainSize}")
# Use combined alignment for operations
geometry = parted.Geometry(device, start=0, length=device.length)
test_sector = 4096
aligned_sector = combined_alignment.alignUp(geometry, test_sector)
print(f"Sector {test_sector} aligned to {aligned_sector}")Different alignment requirements serve different purposes:
device.getMinimumAlignment()device.getOptimumAlignment()Proper alignment is crucial for:
Install with Tessl CLI
npx tessl i tessl/pypi-pyparted