Here’s a quick script I created today for creating and mounting a ramdisk in OSX:
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 | #!/usr/bin/env python import os, sys from subprocess import call from getopt import gnu_getopt, GetoptError def createRamdisk(vol_name, disk_size): dsize = (int(disk_size)*1024)*2 cmd = 'diskutil quiet erasevolume HFS+ "%s" $(hdiutil attach -nomount ram://%i)' %(vol_name, dsize) print "Creating %sMB Ramdisk...\n" %disk_size res = call(cmd, shell=True) if res == 0: print 'Ramdisk "%s" Successfully Created and Mounted.' %vol_name else: print 'Error creating Ramdisk' def usage(): sys.exit( "Usage: %s -n <Volume Name> -s <size in Megabytes>\n" %(sys.argv[0]) ) def main(): SIZE = VOLNAME = None try: options, remainder = gnu_getopt(sys.argv[1:], 's:n:h') for opt, arg in options: if opt in '-s': SIZE = arg elif opt in '-n': VOLNAME = arg elif opt in '-h': usage() except GetoptError, err: print "\nWarning:",err.msg,'\n' usage() if SIZE and VOLNAME: createRamdisk(VOLNAME, SIZE) else: usage() if __name__ == '__main__': main() |
EDIT: Here is a simplified version, using ‘optparse’ intead of ‘getopt’:
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 | #!/usr/bin/env python import os, sys from subprocess import call import optparse def createRamdisk(vol_name, disk_size): dsize = (int(disk_size)*1024)*2 cmd = 'diskutil quiet erasevolume HFS+ "%s" $(hdiutil attach -nomount ram://%i)' %(vol_name, dsize) print "Creating %sMB Ramdisk...\n" %disk_size res = call(cmd, shell=True) if res == 0: print 'Ramdisk "%s" Successfully Created and Mounted.' %vol_name else: print 'Error creating Ramdisk' def main(): p = optparse.OptionParser() p.add_option('--volname', '-n', default='RamDisk') p.add_option('--volsize','-s', default=256) options, arguments = p.parse_args() if options.volsize and options.volname: createRamdisk(options.volname, options.volsize) if __name__ == '__main__': main() |
‘optparse’ is the easier approach, because it handles errors for you, and also automatically displays help via the ‘-h’ switch.
It provides both with no additional code required on the part of the programmer.
