Skip to content

Instantly share code, notes, and snippets.

@MetroWind
Created December 6, 2012 22:18
Show Gist options
  • Save MetroWind/4229003 to your computer and use it in GitHub Desktop.
Save MetroWind/4229003 to your computer and use it in GitHub Desktop.
Quickly create a ramdisk in Mac
#!/usr/bin/env python3
# Usage: $0 SIZE
#
# SIZE can be string like "512k", "1G"...
SectorSize = 512 # Bytes
SIZE_UNITS = {'b': 1.0, 'c': 1.0, 'w': 2.0, 'k': 1024.0,
'M': 1024.0 * 1024.0, 'G': 1024.0 ** 3.0,
'T': 1024.0 ** 4.0, 'P': 1024.0 ** 5.0,
}
def sizeInBytes(size_str):
"""Returns the size in bytes corresponding to `size_str', which is
something like "2G", "2.5k", etc. If no unit is specified, byte is assumed. Valid size units
are 'b', 'c' (1b), 'w' (2b), 'k', 'M', 'G', 'T', and 'P'.
"""
Unit = size_str[-1]
if Unit in SIZE_UNITS:
Number = float(size_str[:-1])
return int(Number * SIZE_UNITS[Unit])
else:
return int(size_str)
def makeRamDisk(size_in_byte):
NSectors = int(size_in_byte / SectorSize)
import subprocess as SubP
RtVal = SubP.call(\
'diskutil erasevolume HFS+ "ramdisk" $(hdiutil attach -nomount ram://{})'.format(NSectors),
shell=True)
if RtVal != 0:
raise RuntimeError("Failed to make ram disk... Diskutil returned {}.".format(RtnVal))
def main(argv):
if len(argv) != 2:
print("Usage: {} SIZE".format(argv[0]))
print()
print('SIZE can be string like "512k", "1G"...')
return -1
Size = argv[1]
makeRamDisk(sizeInBytes(Size))
return 0
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment