HowTo: Using Python XPCOM to modify machine configuration

This is for discussing general topics about how to use VirtualBox.
Post Reply
kihjin
Posts: 71
Joined: 18. Nov 2008, 21:30
Primary OS: Ubuntu other
VBox Version: OSE self-compiled
Guest OSses: Ubuntu, Windows XP

HowTo: Using Python XPCOM to modify machine configuration

Post 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
kihjin
Posts: 71
Joined: 18. Nov 2008, 21:30
Primary OS: Ubuntu other
VBox Version: OSE self-compiled
Guest OSses: Ubuntu, Windows XP

Re: HowTo: Using Python XPCOM to modify machine configuration

Post 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()

Post Reply