'Taking Screenshot's using python using the Virtualbox API

I'm trying to take screenshots from my guest Virtualbox session using a python script running in the host. From the research I did the best way of doing this is accessing the VirtualBox API and using COM constants in order to make a screenshot. However, every time I try to run the script I get an attribute error:

Traceback (most recent call last):
  File "D:\computer_vision_scripts\take_screenshot.py", line 29, in <module>
    take_screenshot('Windows 10 Pro')
  File "D:\computer_vision_scripts\take_screenshot.py", line 16, in take_screenshot
    machine.LockMachine(session, constants.LockType_Shared)
  File "C:\Users\me\AppData\Roaming\Python\Python39\site-packages\win32com\client\__init__.py", line 180, in __getattr__
    raise AttributeError(a)
AttributeError: LockType_Shared

The script I am using comes from https://floatingoctothorpe.uk/2018/automating-virtualbox-screenshots-with-python.html

And looks like this when seen in the file version:

import win32com.client
from win32com.client import constants

def take_screenshot(vm_name, screenshot_path='screenshot.png'):
    """Create a VM Screenshot for a given VM"""

    vbox = win32com.client.Dispatch("VirtualBox.VirtualBox")
    session = win32com.client.Dispatch("VirtualBox.Session")

    machine = vbox.FindMachine(vm_name)

    machine.LockMachine(session, constants.LockType_Shared)

    display = session.Console.Display
    width, height, _, _, _, _ = display.GetScreenResolution(0)
    screenshot = display.TakeScreenShotToArray(0, width, height,
                                               constants.BitmapFormat_PNG)

    session.UnlockMachine()

    with open(screenshot_path, 'wb') as output_png:
        output_png.write(screenshot.tobytes())

if __name__ == '__main__':
    take_screenshot('Windows 10 Pro')

Does anyone know what I should do in order to make it work?



Solution 1:[1]

I faced the same issue. Solved it like this:

  1. Add this:

    import virtualbox

    from virtualbox import library

  2. Change

machine.LockMachine(session, constants.LockType_Shared)

by

machine.LockMachine(session, virtualbox.library.LockType.shared)

and

screenshot = display.TakeScreenShotToArray(0, width, height,constants.BitmapFormat_PNG)

by

screenshot = display.TakeScreenShotToArray(0, width, height, virtualbox.library.BitmapFormat.png)

Found this solution here: https://github.com/sethmlarson/virtualbox-python/blob/master/tests/test_test_vm.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konstantin