Page 1 of 1

HowTo: Using Python XPCOM to modify machine configuration

Posted: 19. May 2011, 06:48
by kihjin
Applies to VirtualBox 4.0.8

I never found a complete example of this anywhere and the SDKRef loosely refers to this process without giving an example. Hopefully this makes life easier for others. This example illustrate how to change the memory of a system.

Code: Select all

>>> import vboxapi
>>> vbm = vboxapi.VirtualBoxManager(None, None)
>>> m = vbm.vbox.findMachine("example")
>>> session = vbm.mgr.getSessionObject(vbm.vbox)
>>> m.lockMachine(session, vbm.constants.LockType_Write)
>>> session.machine.memorySize = 1234
>>> session.machine.saveSettings()
>>> session.unlockMachine()
FYI... if you're going to use the above in production level code, be sure to place it the lock/unlock in a try finally block, otherwise bad things will occur if an error results in a failure to unlock, e.g.

Code: Select all

>>> try:
...    m.lockMachine(session, vbm.constants.LockType_Write)
...    session.machine.memorySize = 1234
...    session.machine.saveSettings()
>>> finally:
...    session.unlockMachine()
This still leaves out a lot of error checking, so use this as a template and check with the SDKRef

Re: HowTo: Using Python XPCOM to modify machine configuration

Posted: 19. May 2011, 09:42
by kihjin
Using a python context manager...

Code: Select all

class MachineLocker():
	def __init__(self, session, machine, locktype):
		self.session = session
		self.machine = machine
		self.locktype = locktype
	def __enter__(self):
		self.machine.lockMachine(self.session, self.locktype)
		return self.session
	def __exit__(self, exc_type, exc_val, exc_tb):
		self.session.unlockMachine()
		return False

>>> import vboxapi
>>> vbm = vboxapi.VirtualBoxManager(None, None)
>>> m = vbm.vbox.findMachine("example")
>>> session = vbm.mgr.getSessionObject(vbm.vbox)
>>> with MachineLocker(session, m, vbm.constants.LockType_Write) as session:
...     session.machine.memorySize = 1241
...     session.machine.saveSettings()