Pause & Resume VirtualBox VM in OSX on Focus change
This little script will pause and resume a virtual machine running under VirtualBox when the window focus changes. It resumes (unpause) the machine whenever its window gets the mouse focus, and it pauses the VM whenever it loses focus.
It is useful for when you have an alternate "desktop" within a VM, so that it only runs whenever you are doing something in it.
#!/usr/bin/python
try:
from AppKit import NSWorkspace
except ImportError:
print "Can't import AppKit -- maybe you're running python from brew?"
print "Try running with Apple's /usr/bin/python instead."
exit(1)
from datetime import datetime
from time import sleep
import os
last_active_name = None
while True:
active_app = NSWorkspace.sharedWorkspace().activeApplication()
if active_app['NSApplicationName'] != last_active_name:
if last_active_name == 'VirtualBox VM':
os.system('VBoxManage controlvm db3bd778-3e91-4834-8730-1a6e3f5e59c3 pause')
last_active_name = active_app['NSApplicationName']
if last_active_name == 'VirtualBox VM':
os.system('VBoxManage controlvm db3bd778-3e91-4834-8730-1a6e3f5e59c3 resume')
print '%s: %s [%s]' % (
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
active_app['NSApplicationName'],
active_app['NSApplicationPath']
)
sleep(1)