如何通过Python使用COM控制VirtualBox?
我正在尝试通过Python控制最新的Sun VirtualBox,使用它的COM接口。但是,不幸的是,下面的代码没有成功:
import win32com.client
VBOX_GUID = "{B1A7A4F2-47B9-4A1E-82B2-07CCD5323C3F}"
try :
oVbox = win32com.client.Dispatch( VBOX_GUID )
oVbox.FindMachine( "kubuntu" )
except Exception as oEx:
print str( oEx )
出现的错误是“(-2147467262, '不支持这样的接口', None, None)”。看起来问题出在我用Python处理COM接口的部分。有没有人能帮我看看,看看我哪里做错了?
1 个回答
3
问题在于,FindMachine("kubuntu")
返回的对象不支持 IDispatch 接口
,而 win32com 也不支持这个接口。
你可以使用我的 comtypes
包,链接在这里:http://starship.python.net/crew/theller/comtypes/,但是你需要对这个包里的版本进行一些修改,才能让它和 VirtualBox 的类型库一起工作。
下面是一个演示示例:
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from comtypes.client import CreateObject
>>> box = CreateObject("VirtualBox.VirtualBox")
>>> m = box.FindMachine("Fedora")
>>> print m.State
4
>>> print m.CpuCount
1
>>> print m.Name
Fedora
>>>
这里是你需要的补丁:
Index: automation.py
===================================================================
--- automation.py (revision 507)
+++ automation.py (working copy)
@@ -753,6 +753,8 @@
c_float: VT_R4,
c_double: VT_R8,
+ c_ulonglong: VT_I8,
+
VARIANT_BOOL: VT_BOOL,
BSTR: VT_BSTR,