[vbox-dev] Context Manager for VM Locking in Python API Bindings

Josh Wright jshwright at gmail.com
Thu Sep 2 17:01:10 GMT 2010


The new locking/unlocking stuff in 3.3 (4.0?) is nice, and certainly a
lot more intuitive than the previous openSession stuff. However, I
find obtaining and managing a lock is still pretty verbose, and it's
the perfect use case for a context manager (in Python 2.5+). The
context manager I use can be found below. While there's certainly room
for improvement, any chance for something like this to be added to
vboxapi in 3.3 (4.0?)?

class LockVM(object):
    ''' Provide a context manager for obtaining a mutable VM and the associated
        session object (both items are returned in a tuple). Since it's assumed
        you'll be making changes to the vm that you'd like to save when using a
        Write lock, saveSettings() will be called when the context exits.

        >>> mgr = vboxapi.VirtualBoxManager(None, None)
        >>> vm = mgr.vbox.findMachine('My VM')
        >>> with LockVM(mgr, vm) as (mutable_vm, session):
        ...     mutable_vm.memorySize(1024)
        >>>
    '''

    def __init__(self, mgr, vm, lock_type = 'LockType_Write'):
        self.mgr = mgr
        self.session = self.mgr.mgr.getSessionObject(self.mgr.vbox)
        self.vm = vm
        self.lock_type = lock_type

    def __enter__(self):
        self.vm.lockMachine(self.session, getattr(self.mgr.constants,
lock_type))
        return (self.session.machine, self.session)

    def __exit__(self, type, value, traceback):
        if self.lock_type == 'LockType_Write':
            self.session.machine.saveSettings()
        self.session.unlockMachine()


~JW




More information about the vbox-dev mailing list