VirtualBox

Changeset 54057 in vbox


Ignore:
Timestamp:
Feb 2, 2015 12:35:10 PM (10 years ago)
Author:
vboxsync
Message:

Main/glue/vboxapi.py: support for python3 (so far Windows only, PyXPCOM library adaptions missing), contributed by Ilya Kulakov. Thanks!

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Main/glue/vboxapi.py

    r51415 r54057  
    66
    77__copyright__ = \
    8 """
    9 Copyright (C) 2009-2013 Oracle Corporation
    10 
    11 This file is part of VirtualBox Open Source Edition (OSE), as
    12 available from http://www.virtualbox.org. This file is free software;
    13 you can redistribute it and/or modify it under the terms of the GNU
    14 General Public License (GPL) as published by the Free Software
    15 Foundation, in version 2 as it comes in the "COPYING" file of the
    16 VirtualBox OSE distribution. VirtualBox OSE is distributed in the
    17 hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
    18 """
     8    """
     9    Copyright (C) 2009-2015 Oracle Corporation
     10
     11    This file is part of VirtualBox Open Source Edition (OSE), as
     12    available from http://www.virtualbox.org. This file is free software;
     13    you can redistribute it and/or modify it under the terms of the GNU
     14    General Public License (GPL) as published by the Free Software
     15    Foundation, in version 2 as it comes in the "COPYING" file of the
     16    VirtualBox OSE distribution. VirtualBox OSE is distributed in the
     17    hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
     18    """
    1919__version__ = "$Revision$"
    2020
     
    2424
    2525# Standard Python imports.
    26 import sys, os
     26import os
     27import sys
    2728import traceback
    2829
     30
     31if sys.version_info >= (3, 0):
     32    xrange = range
     33    long = int
     34    import builtins
     35    print_ = getattr(builtins, 'print', None)
     36elif sys.version_info >= (2, 6):
     37    import __builtin__
     38    print_ = getattr(__builtin__, 'print', None)
     39else:
     40    def print_(*args, **kwargs):
     41        """The new-style print function for Python 2.4 and 2.5."""
     42        fp = kwargs.pop("file", sys.stdout)
     43        if fp is None:
     44            return
     45
     46        def write(data):
     47            if not isinstance(data, basestring):
     48                data = str(data)
     49            # If the file has an encoding, encode unicode with it.
     50            if isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None:
     51                errors = getattr(fp, "errors", None)
     52                if errors is None:
     53                    errors = "strict"
     54                data = data.encode(fp.encoding, errors)
     55            fp.write(data)
     56
     57        want_unicode = False
     58        sep = kwargs.pop("sep", None)
     59        if sep is not None:
     60            if isinstance(sep, unicode):
     61                want_unicode = True
     62            elif not isinstance(sep, str):
     63                raise TypeError("sep must be None or a string")
     64        end = kwargs.pop("end", None)
     65        if end is not None:
     66            if isinstance(end, unicode):
     67                want_unicode = True
     68            elif not isinstance(end, str):
     69                raise TypeError("end must be None or a string")
     70        if kwargs:
     71            raise TypeError("invalid keyword arguments to print()")
     72        if not want_unicode:
     73            for arg in args:
     74                if isinstance(arg, unicode):
     75                    want_unicode = True
     76                    break
     77        if want_unicode:
     78            newline = unicode("\n")
     79            space = unicode(" ")
     80        else:
     81            newline = "\n"
     82            space = " "
     83        if sep is None:
     84            sep = space
     85        if end is None:
     86            end = newline
     87        for i, arg in enumerate(args):
     88            if i:
     89                write(sep)
     90            write(arg)
     91        write(end)
    2992
    3093#
     
    38101    VBoxBinDir = "%VBOX_INSTALL_PATH%"
    39102else:
    40     VBoxBinDir = os.path.abspath(VBoxBinDir);
     103    VBoxBinDir = os.path.abspath(VBoxBinDir)
    41104
    42105if VBoxSdkDir is None:
     
    44107    VBoxSdkDir = "%VBOX_SDK_PATH%"
    45108else:
    46     VBoxSdkDir = os.path.abspath(VBoxSdkDir);
     109    VBoxSdkDir = os.path.abspath(VBoxSdkDir)
    47110
    48111os.environ["VBOX_PROGRAM_PATH"] = VBoxBinDir
     
    54117# Import the generated VirtualBox constants.
    55118#
    56 from VirtualBox_constants import VirtualBoxReflectionInfo
     119from .VirtualBox_constants import VirtualBoxReflectionInfo
    57120
    58121
     
    110173        if self.isMscom:
    111174            (values, names, objects, names_out, objects_out, units, scales, sequence_numbers,
    112                 indices, lengths) = self.collector.queryMetricsData(names, objects)
     175             indices, lengths) = self.collector.queryMetricsData(names, objects)
    113176        else:
    114177            (values, names_out, objects_out, units, scales, sequence_numbers,
    115                 indices, lengths) = self.collector.queryMetricsData(names, objects)
     178             indices, lengths) = self.collector.queryMetricsData(names, objects)
    116179        out = []
    117180        for i in xrange(0, len(names_out)):
     
    122185                fmt = '%d %s'
    123186            out.append({
    124                 'name':str(names_out[i]),
    125                 'object':str(objects_out[i]),
    126                 'unit':str(units[i]),
    127                 'scale':scale,
    128                 'values':[int(values[j]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))],
    129                 'values_as_string':'['+', '.join([fmt % (int(values[j])/scale, units[i]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))])+']'
     187                'name': str(names_out[i]),
     188                'object': str(objects_out[i]),
     189                'unit': str(units[i]),
     190                'scale': scale,
     191                'values': [int(values[j]) for j in xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))],
     192                'values_as_string': '[' + ', '.join([fmt % (int(values[j]) / scale, units[i]) for j in
     193                                                     xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))]) + ']'
    130194            })
    131195        return out
     196
    132197
    133198#
     
    145210}
    146211
     212
    147213def _CustomGetAttr(self, sAttr):
    148214    """ Our getattr replacement for DispatchBaseClass. """
    149215    # Fastpath.
    150     oRet = self.__class__.__dict__.get(sAttr);
    151     if oRet != None:
    152         return oRet;
     216    oRet = self.__class__.__dict__.get(sAttr)
     217    if oRet is not None:
     218        return oRet
    153219
    154220    # Try case-insensitivity workaround for class attributes (COM methods).
    155     sAttrLower = sAttr.lower();
    156     for sKey in self.__class__.__dict__.keys():
    157         if sKey.lower() == sAttrLower:
    158             self.__class__.__dict__[sAttr] = self.__class__.__dict__[sKey]
    159             return getattr(self, sKey)
     221    sAttrLower = sAttr.lower()
     222    for k in self.__class__.__dict__.keys():
     223        if k.lower() == sAttrLower:
     224            setattr(self.__class__, sAttr, self.__class__.__dict__[k])
     225            return getattr(self, k)
    160226
    161227    # Slow path.
     
    164230    except AttributeError:
    165231        return _g_dCOMForward['getattr'](self, sAttr)
     232
    166233
    167234def _CustomSetAttr(self, sAttr, oValue):
     
    173240
    174241
    175 
    176242class PlatformBase(object):
    177243    """
     
    180246
    181247    def __init__(self, aoParams):
    182         _ = aoParams;
     248        _ = aoParams
    183249
    184250    def getVirtualBox(self):
     
    186252        Gets a the IVirtualBox singleton.
    187253        """
    188         return None;
     254        return None
    189255
    190256    def getSessionObject(self, oIVBox):
     
    197263        See also openMachineSession.
    198264        """
    199         _ = oIVBox;
    200         return None;
     265        _ = oIVBox
     266        return None
    201267
    202268    def getType(self):
    203269        """ Returns the platform type (class name sans 'Platform'). """
    204         return None;
     270        return None
    205271
    206272    def isRemote(self):
     
    218284        returning arrays.
    219285        """
    220         _ = oInterface;
    221         _ = sAttrib;
    222         return None;
     286        _ = oInterface
     287        _ = sAttrib
     288        return None
    223289
    224290    def initPerThread(self):
     
    226292        Does backend specific initialization for the calling thread.
    227293        """
    228         return True;
     294        return True
    229295
    230296    def deinitPerThread(self):
     
    232298        Does backend specific uninitialization for the calling thread.
    233299        """
    234         return True;
     300        return True
    235301
    236302    def createListener(self, oImplClass, dArgs):
     
    250316        Use passive listeners for COM and web services.
    251317        """
    252         _ = oImplClass;
    253         _ = dArgs;
    254         raise Exception("No active listeners for this platform");
    255         return None;
     318        _ = oImplClass
     319        _ = dArgs
     320        raise Exception("No active listeners for this platform")
    256321
    257322    def waitForEvents(self, cMsTimeout):
     
    270335        that initialized VirtualBoxManager) or if the time isn't an integer.
    271336        """
    272         _ = cMsTimeout;
    273         return 2;
     337        _ = cMsTimeout
     338        return 2
    274339
    275340    def interruptWaitEvents(self):
     
    280345        Returns True on success, False on failure.
    281346        """
    282         return False;
     347        return False
    283348
    284349    def deinit(self):
     
    286351        Unitializes the platform specific backend.
    287352        """
    288         return None;
     353        return None
    289354
    290355    def queryInterface(self, oIUnknown, sClassName):
     
    295360        sClassName is the name of the interface we're asking for.
    296361        """
    297         return None;
     362        return None
    298363
    299364    #
     
    305370        Returns the COM status code from the VBox API given exception.
    306371        """
    307         return None;
     372        return None
    308373
    309374    def xcptIsDeadInterface(self, oXcpt):
     
    311376        Returns True if the exception indicates that the interface is dead, False if not.
    312377        """
    313         return False;
     378        return False
    314379
    315380    def xcptIsEqual(self, oXcpt, hrStatus):
     
    324389        """
    325390        try:
    326             hrXcpt = self.xcptGetStatus(oXcpt);
     391            hrXcpt = self.xcptGetStatus(oXcpt)
    327392        except AttributeError:
    328             return False;
     393            return False
    329394        if hrXcpt == hrStatus:
    330             return True;
     395            return True
    331396
    332397        # Fudge for 32-bit signed int conversion.
    333         if hrStatus > 0x7fffffff and hrStatus <= 0xffffffff and hrXcpt < 0:
     398        if 0x7fffffff < hrStatus <= 0xffffffff and hrXcpt < 0:
    334399            if (hrStatus - 0x100000000) == hrXcpt:
    335                 return True;
    336         return False;
     400                return True
     401        return False
    337402
    338403    def xcptGetMessage(self, oXcpt):
     
    342407        Raises exception if oXcpt isn't our kind of exception object.
    343408        """
    344         return None;
     409        return None
    345410
    346411    def xcptGetBaseXcpt(self):
     
    348413        Returns the base exception class.
    349414        """
    350         return None;
     415        return None
    351416
    352417    def xcptSetupConstants(self, oDst):
     
    354419        Copy/whatever all error constants onto oDst.
    355420        """
    356         return oDst;
     421        return oDst
    357422
    358423    @staticmethod
     
    363428        for sAttr in dir(oSrc):
    364429            if sAttr[0].isupper() and (sAttr[1].isupper() or sAttr[1] == '_'):
    365                 oAttr = getattr(oSrc, sAttr);
     430                oAttr = getattr(oSrc, sAttr)
    366431                if type(oAttr) is int:
    367                     setattr(oDst, sAttr, oAttr);
    368         return oDst;
    369 
     432                    setattr(oDst, sAttr, oAttr)
     433        return oDst
    370434
    371435
     
    380444    #          are changed.  Fortunately this isn't very often.
    381445    # @{
    382     VBOX_TLB_GUID  = '{D7569351-1750-46F0-936E-BD127D5BC264}'
    383     VBOX_TLB_LCID  = 0
     446    VBOX_TLB_GUID = '{D7569351-1750-46F0-936E-BD127D5BC264}'
     447    VBOX_TLB_LCID = 0
    384448    VBOX_TLB_MAJOR = 1
    385449    VBOX_TLB_MINOR = 3
     
    387451
    388452    def __init__(self, dParams):
    389         PlatformBase.__init__(self, dParams);
     453        PlatformBase.__init__(self, dParams)
    390454
    391455        #
     
    404468        import threading
    405469
    406         self.winerror = winerror;
    407 
    408         pid      = GetCurrentProcess()
     470        self.winerror = winerror
     471
     472        pid = GetCurrentProcess()
    409473        self.tid = GetCurrentThreadId()
    410474        handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS)
     
    416480        if _g_dCOMForward['setattr'] is None:
    417481            _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__']
    418             DispatchBaseClass.__dict__['__getattr__'] = _CustomGetAttr
    419482            _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__']
    420             DispatchBaseClass.__dict__['__setattr__'] = _CustomSetAttr
     483            setattr(DispatchBaseClass, '__getattr__', _CustomGetAttr)
     484            setattr(DispatchBaseClass, '__setattr__', _CustomSetAttr)
    421485
    422486        # Hack the exception base class so the users doesn't need to check for
     
    428492        # versioning rules).
    429493        #
    430         self.flushGenPyCache(win32com.client.gencache);
    431         win32com.client.gencache.EnsureDispatch('VirtualBox.Session');
    432         win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox');
     494        self.flushGenPyCache(win32com.client.gencache)
     495        win32com.client.gencache.EnsureDispatch('VirtualBox.Session')
     496        win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox')
    433497
    434498        self.oIntCv = threading.Condition()
    435         self.fInterrupted = False;
    436 
    437         _ = dParams;
     499        self.fInterrupted = False
     500
     501        _ = dParams
    438502
    439503    def flushGenPyCache(self, oGenCache):
     
    451515        # need to cover it as well.)
    452516        #
    453         sName    = oGenCache.GetGeneratedFileName(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID,
    454                                                   self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR);
    455         sGenPath = oGenCache.GetGeneratePath();
     517        sName = oGenCache.GetGeneratedFileName(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID,
     518                                               self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR)
     519        sGenPath = oGenCache.GetGeneratePath()
    456520        if len(sName) > 36 and len(sGenPath) > 5:
    457             sTypelibPath = os.path.join(sGenPath, sName);
     521            sTypelibPath = os.path.join(sGenPath, sName)
    458522            if os.path.isdir(sTypelibPath):
    459                 import shutil;
    460                 shutil.rmtree(sTypelibPath, ignore_errors = True);
     523                import shutil
     524                shutil.rmtree(sTypelibPath, ignore_errors=True)
    461525
    462526        #
    463527        # Ensure that our typelib is valid.
    464528        #
    465         return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR);
     529        return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR)
    466530
    467531    def getSessionObject(self, oIVBox):
     
    494558            raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() '
    495559                            'returns new gateway objects all the time, thus breaking EventQueue '
    496                             'assumptions about the listener interface pointer being constants between calls ');
     560                            'assumptions about the listener interface pointer being constants between calls ')
    497561        # Did this code ever really work?
    498562        d = {}
    499563        d['BaseClass'] = oImplClass
    500         d['dArgs']     = dArgs
    501         d['tlb_guid']  = PlatformMSCOM.VBOX_TLB_GUID
     564        d['dArgs'] = dArgs
     565        d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID
    502566        d['tlb_major'] = PlatformMSCOM.VBOX_TLB_MAJOR
    503567        d['tlb_minor'] = PlatformMSCOM.VBOX_TLB_MINOR
    504         str = ""
    505         str += "import win32com.server.util\n"
    506         str += "import pythoncom\n"
    507 
    508         str += "class ListenerImpl(BaseClass):\n"
    509         str += "   _com_interfaces_ = ['IEventListener']\n"
    510         str += "   _typelib_guid_ = tlb_guid\n"
    511         str += "   _typelib_version_ = tlb_major, tlb_minor\n"
    512         str += "   _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n"
     568        str_ = ""
     569        str_ += "import win32com.server.util\n"
     570        str_ += "import pythoncom\n"
     571
     572        str_ += "class ListenerImpl(BaseClass):\n"
     573        str_ += "   _com_interfaces_ = ['IEventListener']\n"
     574        str_ += "   _typelib_guid_ = tlb_guid\n"
     575        str_ += "   _typelib_version_ = tlb_major, tlb_minor\n"
     576        str_ += "   _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n"
    513577        # Maybe we'd better implement Dynamic invoke policy, to be more flexible here
    514         str += "   _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"
     578        str_ += "   _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"
    515579
    516580        # capitalized version of listener method
    517         str += "   HandleEvent=BaseClass.handleEvent\n"
    518         str += "   def __init__(self): BaseClass.__init__(self, dArgs)\n"
    519         str += "result = win32com.server.util.wrap(ListenerImpl())\n"
    520         exec(str, d, d)
     581        str_ += "   HandleEvent=BaseClass.handleEvent\n"
     582        str_ += "   def __init__(self): BaseClass.__init__(self, dArgs)\n"
     583        str_ += "result = win32com.server.util.wrap(ListenerImpl())\n"
     584        exec(str_, d, d)
    521585        return d['result']
    522586
     
    525589        from win32event import INFINITE
    526590        from win32event import MsgWaitForMultipleObjects, \
    527                                QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0
     591            QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0
    528592        from pythoncom import PumpWaitingMessages
    529593        import types
    530594
    531         if not isinstance(timeout, types.IntType):
     595        if not isinstance(timeout, int):
    532596            raise TypeError("The timeout argument is not an integer")
    533         if (self.tid != GetCurrentThreadId()):
     597        if self.tid != GetCurrentThreadId():
    534598            raise Exception("wait for events from the same thread you inited!")
    535599
     
    539603            cMsTimeout = timeout
    540604        rc = MsgWaitForMultipleObjects(self.handles, 0, cMsTimeout, QS_ALLINPUT)
    541         if rc >= WAIT_OBJECT_0 and rc < WAIT_OBJECT_0+len(self.handles):
     605        if WAIT_OBJECT_0 <= rc < WAIT_OBJECT_0 + len(self.handles):
    542606            # is it possible?
    543             rc = 2;
    544         elif rc==WAIT_OBJECT_0 + len(self.handles):
     607            rc = 2
     608        elif rc == WAIT_OBJECT_0 + len(self.handles):
    545609            # Waiting messages
    546610            PumpWaitingMessages()
    547             rc = 0;
     611            rc = 0
    548612        else:
    549613            # Timeout
    550             rc = 1;
     614            rc = 1
    551615
    552616        # check for interruption
     
    554618        if self.fInterrupted:
    555619            self.fInterrupted = False
    556             rc = 1;
     620            rc = 1
    557621        self.oIntCv.release()
    558622
    559         return rc;
     623        return rc
    560624
    561625    def interruptWaitEvents(self):
     
    571635        from win32api import PostThreadMessage
    572636        from win32con import WM_USER
     637
    573638        self.oIntCv.acquire()
    574639        self.fInterrupted = True
     
    577642            PostThreadMessage(self.tid, WM_USER, None, 0xf241b819)
    578643        except:
    579             return False;
    580         return True;
     644            return False
     645        return True
    581646
    582647    def deinit(self):
     
    585650
    586651        for h in self.handles:
    587            if h is not None:
    588               CloseHandle(h)
     652            if h is not None:
     653                CloseHandle(h)
    589654        self.handles = None
    590655        pythoncom.CoUninitialize()
     
    600665        hrXcpt = oXcpt.hresult
    601666        if hrXcpt == self.winerror.DISP_E_EXCEPTION:
    602             try:    hrXcpt = oXcpt.excepinfo[5];
    603             except: pass;
    604         return hrXcpt;
     667            try:
     668                hrXcpt = oXcpt.excepinfo[5]
     669            except:
     670                pass
     671        return hrXcpt
    605672
    606673    def xcptIsDeadInterface(self, oXcpt):
    607674        return self.xcptGetStatus(oXcpt) in [
    608             0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE.
    609             0x800706be, -2147023170, # RPC_S_CALL_FAILED.
    610             0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE.
    611             0x80010108, -2147417848, # RPC_E_DISCONNECTED.
    612             0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF
    613         ];
    614 
     675            0x800706ba, -2147023174,  # RPC_S_SERVER_UNAVAILABLE.
     676            0x800706be, -2147023170,  # RPC_S_CALL_FAILED.
     677            0x800706bf, -2147023169,  # RPC_S_CALL_FAILED_DNE.
     678            0x80010108, -2147417848,  # RPC_E_DISCONNECTED.
     679            0x800706b5, -2147023179,  # RPC_S_UNKNOWN_IF
     680        ]
    615681
    616682    def xcptGetMessage(self, oXcpt):
     
    618684            try:
    619685                if len(oXcpt.excepinfo) >= 3:
    620                     sRet = oXcpt.excepinfo[2];
     686                    sRet = oXcpt.excepinfo[2]
    621687                    if len(sRet) > 0:
    622                         return sRet[0:];
     688                        return sRet[0:]
    623689            except:
    624                 pass;
     690                pass
    625691        if hasattr(oXcpt, 'strerror'):
    626692            try:
    627                 sRet = oXcpt.strerror;
     693                sRet = oXcpt.strerror
    628694                if len(sRet) > 0:
    629                     return sRet;
     695                    return sRet
    630696            except:
    631                 pass;
    632         return None;
     697                pass
     698        return None
    633699
    634700    def xcptGetBaseXcpt(self):
    635         import pythoncom;
    636         return pythoncom.com_error;
     701        import pythoncom
     702
     703        return pythoncom.com_error
    637704
    638705    def xcptSetupConstants(self, oDst):
    639         import winerror;
    640         oDst = self.xcptCopyErrorConstants(oDst, winerror);
     706        import winerror
     707
     708        oDst = self.xcptCopyErrorConstants(oDst, winerror)
    641709
    642710        # XPCOM compatability constants.
    643         oDst.NS_OK                    = oDst.S_OK;
    644         oDst.NS_ERROR_FAILURE         = oDst.E_FAIL;
    645         oDst.NS_ERROR_ABORT           = oDst.E_ABORT;
    646         oDst.NS_ERROR_NULL_POINTER    = oDst.E_POINTER;
    647         oDst.NS_ERROR_NO_INTERFACE    = oDst.E_NOINTERFACE;
    648         oDst.NS_ERROR_INVALID_ARG     = oDst.E_INVALIDARG;
    649         oDst.NS_ERROR_OUT_OF_MEMORY   = oDst.E_OUTOFMEMORY;
    650         oDst.NS_ERROR_NOT_IMPLEMENTED = oDst.E_NOTIMPL;
    651         oDst.NS_ERROR_UNEXPECTED      = oDst.E_UNEXPECTED;
    652         return oDst;
     711        oDst.NS_OK = oDst.S_OK
     712        oDst.NS_ERROR_FAILURE = oDst.E_FAIL
     713        oDst.NS_ERROR_ABORT = oDst.E_ABORT
     714        oDst.NS_ERROR_NULL_POINTER = oDst.E_POINTER
     715        oDst.NS_ERROR_NO_INTERFACE = oDst.E_NOINTERFACE
     716        oDst.NS_ERROR_INVALID_ARG = oDst.E_INVALIDARG
     717        oDst.NS_ERROR_OUT_OF_MEMORY = oDst.E_OUTOFMEMORY
     718        oDst.NS_ERROR_NOT_IMPLEMENTED = oDst.E_NOTIMPL
     719        oDst.NS_ERROR_UNEXPECTED = oDst.E_UNEXPECTED
     720        return oDst
    653721
    654722
     
    659727
    660728    def __init__(self, dParams):
    661         PlatformBase.__init__(self, dParams);
    662         sys.path.append(VBoxSdkDir+'/bindings/xpcom/python/')
     729        PlatformBase.__init__(self, dParams)
     730        sys.path.append(VBoxSdkDir + '/bindings/xpcom/python/')
    663731        import xpcom.vboxxpcom
    664732        import xpcom
    665733        import xpcom.components
    666         _ = dParams;
     734        _ = dParams
    667735
    668736    def getSessionObject(self, oIVBox):
    669         _ = oIVBox;
     737        _ = oIVBox
    670738        import xpcom.components
    671739        return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
     
    679747
    680748    def getArray(self, oInterface, sAttrib):
    681         return oInterface.__getattr__('get'+ComifyName(sAttrib))()
     749        return oInterface.__getattr__('get' + ComifyName(sAttrib))()
    682750
    683751    def initPerThread(self):
     
    692760        d = {}
    693761        d['BaseClass'] = oImplClass
    694         d['dArgs']     = dArgs
     762        d['dArgs'] = dArgs
    695763        str = ""
    696764        str += "import xpcom.components\n"
     
    699767        str += "   def __init__(self): BaseClass.__init__(self, dArgs)\n"
    700768        str += "result = ListenerImpl()\n"
    701         exec (str, d, d)
     769        exec(str, d, d)
    702770        return d['result']
    703771
     
    719787
    720788    def xcptGetStatus(self, oXcpt):
    721         return oXcpt.errno;
     789        return oXcpt.errno
    722790
    723791    def xcptIsDeadInterface(self, oXcpt):
    724792        return self.xcptGetStatus(oXcpt) in [
    725             0x80004004, -2147467260, # NS_ERROR_ABORT
    726             0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)
    727         ];
     793            0x80004004, -2147467260,  # NS_ERROR_ABORT
     794            0x800706be, -2147023170,  # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)
     795        ]
    728796
    729797    def xcptGetMessage(self, oXcpt):
    730798        if hasattr(oXcpt, 'msg'):
    731799            try:
    732                 sRet = oXcpt.msg;
     800                sRet = oXcpt.msg
    733801                if len(sRet) > 0:
    734                     return sRet;
     802                    return sRet
    735803            except:
    736                 pass;
    737         return None;
     804                pass
     805        return None
    738806
    739807    def xcptGetBaseXcpt(self):
    740         import xpcom;
    741         return xpcom.Exception;
     808        import xpcom
     809        return xpcom.Exception
    742810
    743811    def xcptSetupConstants(self, oDst):
    744         import xpcom;
    745         oDst = self.xcptCopyErrorConstants(oDst, xpcom.nsError);
     812        import xpcom
     813        oDst = self.xcptCopyErrorConstants(oDst, xpcom.nsError)
    746814
    747815        # COM compatability constants.
    748         oDst.E_ACCESSDENIED           = -2147024891; # see VBox/com/defs.h
    749         oDst.S_OK                     = oDst.NS_OK;
    750         oDst.E_FAIL                   = oDst.NS_ERROR_FAILURE;
    751         oDst.E_ABORT                  = oDst.NS_ERROR_ABORT;
    752         oDst.E_POINTER                = oDst.NS_ERROR_NULL_POINTER;
    753         oDst.E_NOINTERFACE            = oDst.NS_ERROR_NO_INTERFACE;
    754         oDst.E_INVALIDARG             = oDst.NS_ERROR_INVALID_ARG;
    755         oDst.E_OUTOFMEMORY            = oDst.NS_ERROR_OUT_OF_MEMORY;
    756         oDst.E_NOTIMPL                = oDst.NS_ERROR_NOT_IMPLEMENTED;
    757         oDst.E_UNEXPECTED             = oDst.NS_ERROR_UNEXPECTED;
    758         oDst.DISP_E_EXCEPTION         = -2147352567; # For COM compatability only.
    759         return oDst;
     816        oDst.E_ACCESSDENIED = -2147024891 # see VBox/com/defs.h
     817        oDst.S_OK = oDst.NS_OK
     818        oDst.E_FAIL = oDst.NS_ERROR_FAILURE
     819        oDst.E_ABORT = oDst.NS_ERROR_ABORT
     820        oDst.E_POINTER = oDst.NS_ERROR_NULL_POINTER
     821        oDst.E_NOINTERFACE = oDst.NS_ERROR_NO_INTERFACE
     822        oDst.E_INVALIDARG = oDst.NS_ERROR_INVALID_ARG
     823        oDst.E_OUTOFMEMORY = oDst.NS_ERROR_OUT_OF_MEMORY
     824        oDst.E_NOTIMPL = oDst.NS_ERROR_NOT_IMPLEMENTED
     825        oDst.E_UNEXPECTED = oDst.NS_ERROR_UNEXPECTED
     826        oDst.DISP_E_EXCEPTION = -2147352567 # For COM compatability only.
     827        return oDst
    760828
    761829
     
    766834
    767835    def __init__(self, dParams):
    768         PlatformBase.__init__(self, dParams);
     836        PlatformBase.__init__(self, dParams)
    769837        # Import web services stuff.  Fix the sys.path the first time.
    770         sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib');
     838        sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib')
    771839        if sWebServLib not in sys.path:
    772             sys.path.append(sWebServLib);
     840            sys.path.append(sWebServLib)
    773841        import VirtualBox_wrappers
    774842        from VirtualBox_wrappers import IWebsessionManager2
     
    776844        # Initialize instance variables from parameters.
    777845        if dParams is not None:
    778             self.user     = dParams.get("user", "")
     846            self.user = dParams.get("user", "")
    779847            self.password = dParams.get("password", "")
    780             self.url      = dParams.get("url", "")
     848            self.url = dParams.get("url", "")
    781849        else:
    782             self.user     = ""
     850            self.user = ""
    783851            self.password = ""
    784             self.url      = None
    785         self.vbox  = None
    786         self.wsmgr = None;
     852            self.url = None
     853        self.vbox = None
     854        self.wsmgr = None
    787855
    788856    #
     
    808876    def waitForEvents(self, timeout):
    809877        # Webservices cannot do that yet
    810         return 2;
     878        return 2
    811879
    812880    def interruptWaitEvents(self, timeout):
    813881        # Webservices cannot do that yet
    814         return False;
     882        return False
    815883
    816884    def deinit(self):
    817885        try:
    818            disconnect()
     886            disconnect()
    819887        except:
    820            pass
     888            pass
    821889
    822890    def queryInterface(self, oIUnknown, sClassName):
     
    824892        d['oIUnknown'] = oIUnknown
    825893        str = ""
    826         str += "from VirtualBox_wrappers import "+sClassName+"\n"
    827         str += "result = "+sClassName+"(oIUnknown.mgr, oIUnknown.handle)\n"
     894        str += "from VirtualBox_wrappers import " + sClassName + "\n"
     895        str += "result = " + sClassName + "(oIUnknown.mgr, oIUnknown.handle)\n"
    828896        # wrong, need to test if class indeed implements this interface
    829         exec (str, d, d)
     897        exec(str, d, d)
    830898        return d['result']
    831899
     
    836904    def connect(self, url, user, passwd):
    837905        if self.vbox is not None:
    838              self.disconnect()
     906            self.disconnect()
    839907        from VirtualBox_wrappers import IWebsessionManager2
     908
    840909        if url is None:
    841910            url = ""
     
    850919        self.vbox = self.wsmgr.logon(self.user, self.password)
    851920        if not self.vbox.handle:
    852             raise Exception("cannot connect to '"+self.url+"' as '"+self.user+"'")
     921            raise Exception("cannot connect to '" + self.url + "' as '" + self.user + "'")
    853922        return self.vbox
    854923
     
    856925        if self.vbox is not None and self.wsmgr is not None:
    857926            self.wsmgr.logoff(self.vbox)
    858             self.vbox  = None
     927            self.vbox = None
    859928            self.wsmgr = None
    860929
     
    866935# platforms at the same time, so this should be sufficent for most uses and
    867936# be way simpler to use than VirtualBoxManager::oXcptClass.
    868 CurXctpClass = None;
     937CurXctpClass = None
    869938
    870939
     
    884953    class Statuses(object):
    885954        def __init__(self):
    886             pass;
    887 
    888     def __init__(self, sStyle = None, dPlatformParams = None):
     955            pass
     956
     957    def __init__(self, sStyle=None, dPlatformParams=None):
    889958        if sStyle is None:
    890959            if sys.platform == 'win32':
     
    893962                sStyle = "XPCOM"
    894963        if sStyle == 'XPCOM':
    895             self.platform = PlatformXPCOM(dPlatformParams);
     964            self.platform = PlatformXPCOM(dPlatformParams)
    896965        elif sStyle == 'MSCOM':
    897             self.platform = PlatformMSCOM(dPlatformParams);
     966            self.platform = PlatformMSCOM(dPlatformParams)
    898967        elif sStyle == 'WEBSERVICE':
    899             self.platform = PlatformWEBSERVICE(dPlatformParams);
     968            self.platform = PlatformWEBSERVICE(dPlatformParams)
    900969        else:
    901             raise Exception('Unknown sStyle=%s' % (sStyle,));
    902         self.style     = sStyle
    903         self.type      = self.platform.getType()
    904         self.remote    = self.platform.isRemote()
     970            raise Exception('Unknown sStyle=%s' % (sStyle,))
     971        self.style = sStyle
     972        self.type = self.platform.getType()
     973        self.remote = self.platform.isRemote()
    905974        ## VirtualBox API constants (for webservices, enums are symbolic).
    906975        self.constants = VirtualBoxReflectionInfo(sStyle == "WEBSERVICE")
    907976
    908977        ## Status constants.
    909         self.statuses  = self.platform.xcptSetupConstants(VirtualBoxManager.Statuses());
     978        self.statuses = self.platform.xcptSetupConstants(VirtualBoxManager.Statuses())
    910979        ## @todo Add VBOX_E_XXX to statuses? They're already in constants...
    911980        ## Dictionary for errToString, built on demand.
    912         self._dErrorValToName = None;
     981        self._dErrorValToName = None
    913982
    914983        ## The exception class for the selected platform.
    915         self.oXcptClass = self.platform.xcptGetBaseXcpt();
    916         global CurXcptClass;
    917         CurXcptClass = self.oXcptClass;
     984        self.oXcptClass = self.platform.xcptGetBaseXcpt()
     985        global CurXcptClass
     986        CurXcptClass = self.oXcptClass
    918987
    919988        # Get the virtualbox singleton.
    920989        try:
    921990            self.vbox = self.platform.getVirtualBox()
    922         except NameError, ne:
    923             print "Installation problem: check that appropriate libs in place"
     991        except NameError:
     992            print_("Installation problem: check that appropriate libs in place")
    924993            traceback.print_exc()
    925             raise ne
    926         except Exception, e:
    927             print "init exception: ", e
     994            raise
     995        except Exception:
     996            _, e, _ = sys.exc_info()
     997            print_("init exception: ", e)
    928998            traceback.print_exc()
    929999            if self.remote:
     
    9311001            else:
    9321002                raise e
     1003
    9331004        ## @deprecated
    9341005        # This used to refer to a session manager class with only one method
    9351006        # called getSessionObject.  The method has moved into this call.
    936         self.mgr = self;
     1007        self.mgr = self
    9371008
    9381009    def __del__(self):
     
    9441015        This will be incremented when features are added to this file.
    9451016        """
    946         return 3;
    947 
     1017        return 3
    9481018
    9491019    #
    9501020    # Wrappers for self.platform methods.
    9511021    #
    952 
    9531022    def getVirtualBox(self):
    9541023        """ See PlatformBase::getVirtualBox(). """
     
    9571026    def getSessionObject(self, oIVBox):
    9581027        """ See PlatformBase::getSessionObject(). """
    959         return self.platform.getSessionObject(oIVBox);
     1028        return self.platform.getSessionObject(oIVBox)
    9601029
    9611030    def getArray(self, oInterface, sAttrib):
     
    9631032        return self.platform.getArray(oInterface, sAttrib)
    9641033
    965     def createListener(self, oImplClass, dArgs = None):
     1034    def createListener(self, oImplClass, dArgs=None):
    9661035        """ See PlatformBase::createListener(). """
    9671036        return self.platform.createListener(oImplClass, dArgs)
     
    9791048        return self.platform.queryInterface(oIUnknown, sClassName)
    9801049
    981 
    9821050    #
    9831051    # Init and uninit.
    9841052    #
    985 
    9861053    def initPerThread(self):
    9871054        """ See PlatformBase::deinitPerThread(). """
     
    10031070            self.platform.deinit()
    10041071            self.platform = None
    1005         return True;
    1006 
     1072        return True
    10071073
    10081074    #
    10091075    # Utility methods.
    10101076    #
    1011 
    1012     def openMachineSession(self, oIMachine, fPermitSharing = True):
     1077    def openMachineSession(self, oIMachine, fPermitSharing=True):
    10131078        """
    10141079        Attemts to open the a session to the machine.
     
    10161081        Raises exception on failure.
    10171082        """
    1018         oSession = self.mgr.getSessionObject(self.vbox);
     1083        oSession = self.mgr.getSessionObject(self.vbox)
    10191084        if fPermitSharing:
    1020             type = self.constants.LockType_Shared;
     1085            type_ = self.constants.LockType_Shared
    10211086        else:
    1022             type = self.constants.LockType_Write;
    1023         oIMachine.lockMachine(oSession, type);
    1024         return oSession;
     1087            type_ = self.constants.LockType_Write
     1088        oIMachine.lockMachine(oSession, type_)
     1089        return oSession
    10251090
    10261091    def closeMachineSession(self, oSession):
     
    10311096        if oSession is not None:
    10321097            oSession.unlockMachine()
    1033         return True;
     1098        return True
    10341099
    10351100    def getPerfCollector(self, oIVBox):
     
    10541119        return VBoxSdkDir
    10551120
    1056 
    10571121    #
    10581122    # Error code utilities.
    10591123    #
    1060 
    10611124    ## @todo port to webservices!
    1062 
    1063     def xcptGetStatus(self, oXcpt = None):
     1125    def xcptGetStatus(self, oXcpt=None):
    10641126        """
    10651127        Gets the status code from an exception.  If the exception parameter
     
    10671129        """
    10681130        if oXcpt is None:
    1069             oXcpt = sys.exc_info()[1];
    1070         return self.platform.xcptGetStatus(oXcpt);
    1071 
    1072     def xcptIsDeadInterface(self, oXcpt = None):
     1131            oXcpt = sys.exc_info()[1]
     1132        return self.platform.xcptGetStatus(oXcpt)
     1133
     1134    def xcptIsDeadInterface(self, oXcpt=None):
    10731135        """
    10741136        Returns True if the exception indicates that the interface is dead,
     
    10771139        """
    10781140        if oXcpt is None:
    1079             oXcpt = sys.exc_info()[1];
    1080         return self.platform.xcptIsDeadInterface(oXcpt);
    1081 
    1082     def xcptIsOurXcptKind(self, oXcpt = None):
     1141            oXcpt = sys.exc_info()[1]
     1142        return self.platform.xcptIsDeadInterface(oXcpt)
     1143
     1144    def xcptIsOurXcptKind(self, oXcpt=None):
    10831145        """
    10841146        Checks if the exception is one that could come from the VBox API. If
     
    10861148        examined.
    10871149        """
    1088         if self.oXcptClass is None: ## @todo find the exception class for web services!
    1089             return False;
     1150        if self.oXcptClass is None:  # @todo find the exception class for web services!
     1151            return False
    10901152        if oXcpt is None:
    1091             oXcpt = sys.exc_info()[1];
    1092         return isinstance(oXcpt, self.oXcptClass);
     1153            oXcpt = sys.exc_info()[1]
     1154        return isinstance(oXcpt, self.oXcptClass)
    10931155
    10941156    def xcptIsEqual(self, oXcpt, hrStatus):
     
    11041166        """
    11051167        if oXcpt is None:
    1106             oXcpt = sys.exc_info()[1];
    1107         return self.platform.xcptIsEqual(oXcpt, hrStatus);
     1168            oXcpt = sys.exc_info()[1]
     1169        return self.platform.xcptIsEqual(oXcpt, hrStatus)
    11081170
    11091171    def xcptIsNotEqual(self, oXcpt, hrStatus):
     
    11111173        Negated xcptIsEqual.
    11121174        """
    1113         return not self.xcptIsEqual(oXcpt, hrStatus);
    1114 
    1115     def xcptToString(self, hrStatusOrXcpt = None):
     1175        return not self.xcptIsEqual(oXcpt, hrStatus)
     1176
     1177    def xcptToString(self, hrStatusOrXcpt=None):
    11161178        """
    11171179        Converts the specified COM status code, or the status code of the
     
    11211183
    11221184        # Deal with exceptions.
    1123         if hrStatusOrXcpt is None  or self.xcptIsOurXcptKind(hrStatusOrXcpt):
    1124             hrStatus = self.xcptGetStatus(hrStatusOrXcpt);
     1185        if hrStatusOrXcpt is None or self.xcptIsOurXcptKind(hrStatusOrXcpt):
     1186            hrStatus = self.xcptGetStatus(hrStatusOrXcpt)
    11251187        else:
    1126             hrStatus = hrStatusOrXcpt;
     1188            hrStatus = hrStatusOrXcpt
    11271189
    11281190        # Build the dictionary on demand.
    11291191        if self._dErrorValToName is None:
    1130             dErrorValToName = dict();
     1192            dErrorValToName = dict()
    11311193            for sKey in dir(self.statuses):
    11321194                if sKey[0].isupper():
    1133                     oValue = getattr(self.statuses, sKey);
     1195                    oValue = getattr(self.statuses, sKey)
    11341196                    if type(oValue) is int:
    1135                         dErrorValToName[oValue] = sKey;
    1136             self._dErrorValToName = dErrorValToName;
     1197                        dErrorValToName[oValue] = sKey
     1198            self._dErrorValToName = dErrorValToName
    11371199
    11381200        # Do the lookup, falling back on formatting the status number.
    11391201        try:
    1140             sStr = self._dErrorValToName[int(hrStatus)];
     1202            sStr = self._dErrorValToName[int(hrStatus)]
    11411203        except KeyError:
    1142             hrLong = long(hrStatus);
    1143             sStr = '%#x (%d)' % (hrLong, hrLong);
    1144         return sStr;
    1145 
    1146     def xcptGetMessage(self, oXcpt = None):
     1204            hrLong = long(hrStatus)
     1205            sStr = '%#x (%d)' % (hrLong, hrLong)
     1206        return sStr
     1207
     1208    def xcptGetMessage(self, oXcpt=None):
    11471209        """
    11481210        Returns the best error message found in the COM-like exception. If the
     
    11501212        """
    11511213        if oXcpt is None:
    1152             oXcpt = sys.exc_info()[1];
    1153         sRet = self.platform.xcptGetMessage(oXcpt);
     1214            oXcpt = sys.exc_info()[1]
     1215        sRet = self.platform.xcptGetMessage(oXcpt)
    11541216        if sRet is None:
    1155             sRet = self.xcptToString(oXcpt);
    1156         return sRet;
     1217            sRet = self.xcptToString(oXcpt)
     1218        return sRet
    11571219
    11581220    # Legacy, remove in a day or two.
    1159     errGetStatus       = xcptGetStatus
     1221    errGetStatus = xcptGetStatus
    11601222    errIsDeadInterface = xcptIsDeadInterface
    1161     errIsOurXcptKind   = xcptIsOurXcptKind
    1162     errGetMessage      = xcptGetMessage
    1163 
     1223    errIsOurXcptKind = xcptIsOurXcptKind
     1224    errGetMessage = xcptGetMessage
     1225
Note: See TracChangeset for help on using the changeset viewer.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette