Python bindings for GNU parted library providing disk partition management capabilities
—
pyparted provides extensive constants for device types, partition types, flags, units, and other enumerated values. These constants ensure type safety and provide readable code.
Constants for size and unit specifications used throughout the library.
# Sector-based units
UNIT_SECTOR: int # Sectors
UNIT_BYTE: int # Bytes
UNIT_CYLINDER: int # Cylinders
UNIT_CHS: int # Cylinder-Head-Sector
UNIT_PERCENT: int # Percentage
UNIT_COMPACT: int # Compact display
# SI units (decimal, base 1000)
UNIT_KILOBYTE: int # Kilobytes (1,000 bytes)
UNIT_MEGABYTE: int # Megabytes (1,000,000 bytes)
UNIT_GIGABYTE: int # Gigabytes (1,000,000,000 bytes)
UNIT_TERABYTE: int # Terabytes (1,000,000,000,000 bytes)
# IEC units (binary, base 1024)
UNIT_KIBIBYTE: int # Kibibytes (1,024 bytes)
UNIT_MEBIBYTE: int # Mebibytes (1,048,576 bytes)
UNIT_GIBIBYTE: int # Gibibytes (1,073,741,824 bytes)
UNIT_TEBIBYTE: int # Tebibytes (1,099,511,627,776 bytes)Constants identifying different storage device interface types.
DEVICE_UNKNOWN: int # Unknown device type
DEVICE_SCSI: int # SCSI devices
DEVICE_IDE: int # IDE/PATA devices
DEVICE_DAC960: int # DAC960 RAID controller
DEVICE_CPQARRAY: int # Compaq Smart Array
DEVICE_FILE: int # File-based devices (disk images)
DEVICE_ATARAID: int # ATA RAID devices
DEVICE_I2O: int # I2O devices
DEVICE_UBD: int # User-mode block devices
DEVICE_DASD: int # S/390 DASD devices
DEVICE_VIODASD: int # Virtual I/O DASD
DEVICE_SX8: int # Promise SX8 devices
DEVICE_DM: int # Device mapper devices
DEVICE_XVD: int # Xen virtual devices
DEVICE_SDMMC: int # SD/MMC devices
DEVICE_VIRTBLK: int # Virtual block devices
DEVICE_NVME: int # NVMe devicesConstants defining the basic type and role of partitions.
PARTITION_NORMAL: int # Regular primary partition
PARTITION_LOGICAL: int # Logical partition (within extended)
PARTITION_EXTENDED: int # Extended partition container
PARTITION_FREESPACE: int # Free space region (not a real partition)
PARTITION_METADATA: int # Metadata partition (system use)
PARTITION_PROTECTED: int # Protected partition (system use)Constants for partition flags that control partition behavior and properties.
# Basic flags
PARTITION_BOOT: int # Boot/active flag
PARTITION_ROOT: int # Root filesystem flag
PARTITION_SWAP: int # Swap partition flag
PARTITION_HIDDEN: int # Hidden partition flag
PARTITION_RAID: int # Software RAID member
PARTITION_LVM: int # LVM physical volume
PARTITION_LBA: int # LBA addressing required
# System-specific flags
PARTITION_HPSERVICE: int # HP service partition
PARTITION_PALO: int # PA-RISC boot partition
PARTITION_PREP: int # PowerPC PReP boot partition
PARTITION_DIAG: int # Diagnostic partition
PARTITION_LEGACY_BOOT: int # Legacy boot flag
# UEFI/GPT flags
PARTITION_ESP: int # EFI System Partition
PARTITION_BIOS_GRUB: int # BIOS boot partition for GRUB
PARTITION_APPLE_TV_RECOVERY: int # Apple TV recovery partition
# Microsoft flags
PARTITION_MSFT_RESERVED: int # Microsoft Reserved partition
PARTITION_MSFT_DATA: int # Microsoft Basic Data partition (conditional)
PARTITION_IRST: int # Intel Rapid Start Technology (conditional)
# Chrome OS flags
PARTITION_CHROMEOS_KERNEL: int # Chrome OS kernel partition (conditional)
# Linux-specific flags
PARTITION_BLS_BOOT: int # Boot Loader Specification boot (conditional)
PARTITION_LINUX_HOME: int # Linux home partition (conditional)
PARTITION_NO_AUTOMOUNT: int # No auto-mount flag (conditional)
PARTITION_NONFS: int # Non-filesystem partition (conditional)Constants for disk-level flags affecting entire partition tables.
DISK_CYLINDER_ALIGNMENT: int # Cylinder alignment flag
DISK_GPT_PMBR_BOOT: int # GPT protective MBR boot flagConstants for querying disk type capabilities and features.
DISK_TYPE_EXTENDED: int # Supports extended partitions
DISK_TYPE_PARTITION_NAME: int # Supports partition names
DISK_TYPE_PARTITION_TYPE_ID: int # Supports partition type IDs (conditional)
DISK_TYPE_PARTITION_TYPE_UUID: int # Supports partition type UUIDs (conditional)
DISK_TYPE_DISK_UUID: int # Supports disk UUIDs (conditional)
DISK_TYPE_PARTITION_UUID: int # Supports partition UUIDs (conditional)Constants for categorizing exception severity levels.
EXCEPTION_TYPE_INFORMATION: int # Informational message
EXCEPTION_TYPE_WARNING: int # Warning message
EXCEPTION_TYPE_ERROR: int # Error condition
EXCEPTION_TYPE_FATAL: int # Fatal error
EXCEPTION_TYPE_BUG: int # Software bug detected
EXCEPTION_TYPE_NO_FEATURE: int # Feature not supportedConstants for exception handling and resolution options.
EXCEPTION_RESOLVE_UNHANDLED: int # Exception not handled
EXCEPTION_RESOLVE_FIX: int # Fix the problem
EXCEPTION_RESOLVE_YES: int # Yes response
EXCEPTION_RESOLVE_NO: int # No response
EXCEPTION_RESOLVE_OK: int # OK response
EXCEPTION_RESOLVE_RETRY: int # Retry operation
EXCEPTION_RESOLVE_IGNORE: int # Ignore the problem
EXCEPTION_RESOLVE_CANCEL: int # Cancel operationConstants for available exception response options.
EXCEPTION_OPT_OK_CANCEL: int # OK/Cancel options
EXCEPTION_OPT_YES_NO: int # Yes/No options
EXCEPTION_OPT_YES_NO_CANCEL: int # Yes/No/Cancel options
EXCEPTION_OPT_IGNORE_CANCEL: int # Ignore/Cancel options
EXCEPTION_OPT_RETRY_CANCEL: int # Retry/Cancel options
EXCEPTION_OPT_RETRY_IGNORE_CANCEL: int # Retry/Ignore/Cancel optionspyparted provides dictionaries that map constants to human-readable names.
# Unit mappings
units: dict[int, str] # Maps unit constants to names
# Device type mappings
devices: dict[int, str] # Maps device type constants to names
# Partition mappings
partitions: dict[int, str] # Maps partition constants to names
# Type registries
diskType: dict[str, object] # Available disk types
fileSystemType: dict[str, object] # Available filesystem types
diskFlag: dict[str, int] # Available disk flags
partitionFlag: dict[str, int] # Available partition flagsimport parted
device = parted.getDevice('/dev/sda')
# Check device type using constants
if device.type == parted.DEVICE_SCSI:
print("SCSI device")
elif device.type == parted.DEVICE_NVME:
print("NVMe device")
elif device.type == parted.DEVICE_VIRTBLK:
print("Virtual block device")
else:
print(f"Other device type: {device.type}")
# Use dictionary for readable output
device_name = parted.devices.get(device.type, "Unknown")
print(f"Device type: {device_name}")
# List all known device types
print("\nAll device types:")
for type_const, type_name in parted.devices.items():
print(f" {type_name}: {type_const}")import parted
device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
for partition in disk.partitions:
# Check partition type
if partition.type == parted.PARTITION_NORMAL:
type_name = "Primary"
elif partition.type == parted.PARTITION_LOGICAL:
type_name = "Logical"
elif partition.type == parted.PARTITION_EXTENDED:
type_name = "Extended"
else:
type_name = f"Other ({partition.type})"
print(f"Partition {partition.number}: {type_name}")
# Check common flags
flags_set = []
flag_checks = [
(parted.PARTITION_BOOT, "boot"),
(parted.PARTITION_SWAP, "swap"),
(parted.PARTITION_RAID, "raid"),
(parted.PARTITION_LVM, "lvm"),
(parted.PARTITION_ESP, "esp")
]
for flag_const, flag_name in flag_checks:
if partition.isFlagAvailable(flag_const) and partition.getFlag(flag_const):
flags_set.append(flag_name)
if flags_set:
print(f" Flags: {', '.join(flags_set)}")import parted
# Display all available units
print("Available units:")
for unit_const, unit_name in parted.units.items():
print(f" {unit_name}: {unit_const}")
# Use unit constants for calculations
device = parted.getDevice('/dev/sda')
device_bytes = device.length * device.sectorSize
# Convert to different units using constants
size_gb = parted.formatBytes(device_bytes, 'GB')
size_gib = parted.formatBytes(device_bytes, 'GiB')
print(f"Device size: {size_gb:.1f} GB ({size_gib:.1f} GiB)")import parted
device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
# Check what features the disk type supports
features_to_check = [
(parted.DISK_TYPE_EXTENDED, "Extended partitions"),
(parted.DISK_TYPE_PARTITION_NAME, "Partition names")
]
# Add conditional features if available
if hasattr(parted, 'DISK_TYPE_PARTITION_UUID'):
features_to_check.append((parted.DISK_TYPE_PARTITION_UUID, "Partition UUIDs"))
if hasattr(parted, 'DISK_TYPE_DISK_UUID'):
features_to_check.append((parted.DISK_TYPE_DISK_UUID, "Disk UUIDs"))
print(f"Disk type: {disk.type}")
print("Supported features:")
for feature_const, feature_name in features_to_check:
supported = disk.supportsFeature(feature_const)
status = "✓" if supported else "✗"
print(f" {status} {feature_name}")import parted
device = parted.getDevice('/dev/sda')
disk = parted.newDisk(device)
partition = disk.getPartitionByNumber(1)
if partition:
print(f"Partition {partition.number} flag availability:")
# Check all partition flags
all_flags = [
(parted.PARTITION_BOOT, "boot"),
(parted.PARTITION_ROOT, "root"),
(parted.PARTITION_SWAP, "swap"),
(parted.PARTITION_HIDDEN, "hidden"),
(parted.PARTITION_RAID, "raid"),
(parted.PARTITION_LVM, "lvm"),
(parted.PARTITION_LBA, "lba"),
(parted.PARTITION_ESP, "esp"),
(parted.PARTITION_BIOS_GRUB, "bios_grub"),
(parted.PARTITION_PREP, "prep"),
(parted.PARTITION_MSFT_RESERVED, "msft_reserved")
]
# Add conditional flags if available
if hasattr(parted, 'PARTITION_MSFT_DATA'):
all_flags.append((parted.PARTITION_MSFT_DATA, "msft_data"))
for flag_const, flag_name in all_flags:
available = partition.isFlagAvailable(flag_const)
if available:
current_value = partition.getFlag(flag_const)
status = "ON" if current_value else "off"
print(f" ✓ {flag_name}: {status}")
else:
print(f" ✗ {flag_name}: not available")import parted
def custom_exception_handler(exception_type, message, options):
"""Custom exception handler using constants."""
# Determine exception type
if exception_type == parted.EXCEPTION_TYPE_INFORMATION:
print(f"INFO: {message}")
return parted.EXCEPTION_RESOLVE_OK
elif exception_type == parted.EXCEPTION_TYPE_WARNING:
print(f"WARNING: {message}")
return parted.EXCEPTION_RESOLVE_OK
elif exception_type == parted.EXCEPTION_TYPE_ERROR:
print(f"ERROR: {message}")
# Check available options
if options == parted.EXCEPTION_OPT_YES_NO:
response = input("Continue? (y/n): ")
return parted.EXCEPTION_RESOLVE_YES if response.lower() == 'y' else parted.EXCEPTION_RESOLVE_NO
elif options == parted.EXCEPTION_OPT_RETRY_CANCEL:
response = input("Retry? (r/c): ")
return parted.EXCEPTION_RESOLVE_RETRY if response.lower() == 'r' else parted.EXCEPTION_RESOLVE_CANCEL
return parted.EXCEPTION_RESOLVE_UNHANDLED
# Register the handler
parted.register_exn_handler(custom_exception_handler)import parted
def validate_constants():
"""Validate that expected constants exist."""
required_constants = [
'DEVICE_SCSI', 'DEVICE_NVME', 'DEVICE_VIRTBLK',
'PARTITION_NORMAL', 'PARTITION_LOGICAL', 'PARTITION_EXTENDED',
'PARTITION_BOOT', 'PARTITION_SWAP', 'PARTITION_ESP',
'UNIT_SECTOR', 'UNIT_GIGABYTE', 'UNIT_GIBIBYTE'
]
missing = []
for const_name in required_constants:
if not hasattr(parted, const_name):
missing.append(const_name)
if missing:
print(f"Missing constants: {missing}")
return False
else:
print("All required constants available")
return True
# Check optional constants
def check_optional_constants():
"""Check for optional/conditional constants."""
optional_constants = [
'PARTITION_MSFT_DATA',
'PARTITION_CHROMEOS_KERNEL',
'PARTITION_BLS_BOOT',
'DISK_TYPE_PARTITION_UUID'
]
print("Optional constants:")
for const_name in optional_constants:
available = hasattr(parted, const_name)
status = "✓" if available else "✗"
print(f" {status} {const_name}")
validate_constants()
check_optional_constants()Some constants may not be available on all systems or may have conditional availability:
PARTITION_MSFT_DATA - Available on systems with newer libpartedPARTITION_IRST - Intel Rapid Start Technology supportPARTITION_CHROMEOS_KERNEL - Chrome OS kernel partitionDISK_TYPE_PARTITION_UUID - GPT partition UUID supportInstall with Tessl CLI
npx tessl i tessl/pypi-pyparted