1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
"""
functions to deal with a temporary drive with 16 GB size
"""
import tempfile, re
from subprocess import call, Popen, PIPE
def create_drive(size = "16G"):
"""
Create a temporary drive
@param size the size of the drive as a string; "G" is meaning 1024^3
@return a path to the loop device, and the underlying disk file
"""
tmp = tempfile.NamedTemporaryFile(mode='wb', prefix="liveDrive-", delete=False)
m = re.match(r"(\d+)G", size)
if m:
size = int(m.group(1))*(1024**3)
else:
size = 16*(1024**3)
tmp.seek(size-1)
tmp.write(bytes([0x0]))
tmp.close()
loop = ""
# find the next loop's path
with Popen(["/usr/sbin/losetup", "-f"], stdout=PIPE) as proc:
loop = proc.stdout.read().decode("utf-8").strip()
# setup the loop for the temporary file
call(["/usr/sbin/losetup", "-f",tmp.name ])
return loop, tmp.name
def loopDict(loop):
"""
@param loop the path to a loop device
@return a dictionary loop device => list of partitions
"""
lines=[]
with Popen(["/usr/sbin/sfdisk", "-l", loop], stdout=PIPE) as proc:
lines = proc.stdout.read().decode("utf-8").split("\n")
parts=[]
for l in lines:
m = re.match(r"^(/dev/loop[\d+]p[\d+]) .*", l)
if m:
parts.append(m.group(1))
return {loop: parts}
def test_create_drive():
loop, name = create_drive()
print("created", loop, "=>", name)
return
if __name__ == "__main__":
test_create_drive()
|