Skip to content

Instantly share code, notes, and snippets.

@kergoth
Created December 27, 2012 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kergoth/4388948 to your computer and use it in GitHub Desktop.
Save kergoth/4388948 to your computer and use it in GitHub Desktop.
Example use of pyparted to achieve partition alignments with non-devices that the parted command cannot.
#!/usr/bin/env python
import parted
def add_partition(disk, free, align=None, length=None, fs_type=None, type=parted.PARTITION_NORMAL):
start = free.start
if length:
end = start + length - 1
else:
end = free.end
length = free.end - start + 1
if not align:
align = disk.partitionAlignment.intersect(disk.device.optimumAlignment)
if not align.isAligned(free, start):
start = align.alignNearest(free, start)
end_align = parted.Alignment(offset=align.offset - 1, grainSize=align.grainSize)
if not end_align.isAligned(free, end):
end = end_align.alignNearest(free, end)
geometry = parted.Geometry(disk.device, start=start, end=end)
if fs_type:
fs = parted.FileSystem(type=fs_type, geometry=geometry)
else:
fs = None
partition = parted.Partition(disk, type=type, geometry=geometry, fs=fs)
constraint = parted.Constraint(exactGeom=partition.geometry)
disk.addPartition(partition, constraint)
return partition
def get_free_regions(disk, align):
"""Get a filtered list of free regions, excluding the gaps due to partition alignment"""
regions = disk.getFreeSpaceRegions()
new_regions = []
for region in regions:
if region.length > align.grainSize:
new_regions.append(region)
return new_regions
def kib_to_sectors(device, kib):
return parted.sizeToSectors(kib, 'KiB', device.sectorSize)
boot_size = 144584 * 512
align = parted.Alignment(offset=63, grainSize=63*255)
device = parted.Device("./foo")
disk = parted.freshDisk(device, "msdos")
boot_partition = add_partition(disk, get_free_regions(disk, align)[0], align, boot_size / 512, fs_type='fat32')
boot_partition.setFlag(parted.PARTITION_BOOT)
root_partition = add_partition(disk, get_free_regions(disk, align)[0])
disk.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment