VirtualBox

Changeset 59798 in vbox


Ignore:
Timestamp:
Feb 24, 2016 2:35:47 PM (9 years ago)
Author:
vboxsync
Message:

re-applied the Python 3 changes which were backed out in r105674 sans the changes in .cpp

Location:
trunk
Files:
22 edited

Legend:

Unmodified
Added
Removed
  • trunk/Config.kmk

    r59795 r59798  
    64746474        $(MAKE) VBOX_QUICK=1
    64756475
     6476
  • trunk/doc/manual/en_US/SDKRef.xml

    r59795 r59798  
    781781        <xref linkend="glue-python"/>.</para>
    782782
     783        <para>The minimum supported Python version is 2.6.</para>
     784
    783785        <para>As indicated in <xref linkend="webservice-or-com"/>, the
    784786        COM/XPCOM API gives better performance without the SOAP overhead, and
     
    788790        platform<footnote>
    789791            <para>On On Mac OS X only the Python versions bundled with the OS
    790             are officially supported. This means Python 2.3 for 10.4, Python
    791             2.5 for 10.5 and Python 2.5 and 2.6 for 10.6.</para>
     792            are officially supported. This means 2.6 and 2.7 for 10.8 and later.</para>
    792793          </footnote>). On Windows, you can use the Main API from Python if the
    793794          Win32 extensions package for Python<footnote>
    794795            <para>See <ulink
    795796            url="http://sourceforge.net/project/showfiles.php?group_id=78018">http://sourceforge.net/project/showfiles.php?group_id=78018</ulink>.</para>
    796           </footnote> is installed. Version of Python Win32 extensions earlier
     797          </footnote> is installed. Versions of Python Win32 extensions earlier
    797798          than 2.16 are known to have bugs, leading to issues with VirtualBox
    798           Python bindings, and also some early builds of Python 2.5 for Windows
    799           have issues with reporting platform name on some Windows versions, so
    800           please make sure to use latest available Python and Win32
    801           extensions.</para>
     799          Python bindings, so please make sure to use latest available Python
     800          and Win32 extensions.</para>
    802801
    803802        <para>The VirtualBox OOWS for Python relies on the Python ZSI SOAP
     
    14971496        the glue layer if you want to use a different Python
    14981497        installation.</para>
     1498
     1499        <para>The minimum supported Python version is 2.6.</para>
    14991500
    15001501        <para>In this layer, the class
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r59795 r59798  
    22# -*- coding: utf-8 -*-
    33# $Id$
     4
    45"""
    56VirtualBox Python Shell.
     
    1920"""
    2021
     22from __future__ import print_function
     23
    2124__copyright__ = \
    2225"""
    23 Copyright (C) 2009-2015 Oracle Corporation
     26Copyright (C) 2009-2016 Oracle Corporation
    2427
    2528This file is part of VirtualBox Open Source Edition (OSE), as
     
    3437
    3538
    36 import os, sys
     39import os
     40import sys
    3741import traceback
    3842import shlex
     
    4246from optparse import OptionParser
    4347from pprint import pprint
    44 
    4548
    4649
     
    152155                            matches.append(word)
    153156
    154             except Exception, e:
     157            except Exception as e:
    155158                printErr(self.ctx, e)
    156159                if g_fVerbose:
     
    164167
    165168    comps = {}
    166     for (key, _value) in cmds.items():
     169    for (key, _value) in list(cmds.items()):
    167170        comps[key] = None
    168171    completer = CompleterNG(comps, ctx)
     
    189192    try:
    190193        while not progress.completed:
    191             print "%s %%\r" % (colored(str(progress.percent), 'red')),
     194            print("%s %%\r" % (colored(str(progress.percent), 'red')), end="")
    192195            sys.stdout.flush()
    193196            progress.waitForCompletion(wait)
     
    197200        return 1
    198201    except KeyboardInterrupt:
    199         print "Interrupted."
     202        print("Interrupted.")
    200203        ctx['interrupt'] = True
    201204        if progress.cancelable:
    202             print "Canceling task..."
     205            print("Canceling task...")
    203206            progress.cancel()
    204207        return 0
    205208
    206209def printErr(_ctx, e):
    207     oVBoxMgr = _ctx['global'];
     210    oVBoxMgr = _ctx['global']
    208211    if oVBoxMgr.errIsOurXcptKind(e):
    209         print colored('%s: %s' % (oVBoxMgr.xcptToString(e), oVBoxMgr.xcptGetMessage(e)), 'red');
    210     else:
    211         print colored(str(e), 'red')
     212        print(colored('%s: %s' % (oVBoxMgr.xcptToString(e), oVBoxMgr.xcptGetMessage(e)), 'red'))
     213    else:
     214        print(colored(str(e), 'red'))
    212215
    213216def reportError(_ctx, progress):
    214217    errorinfo = progress.errorInfo
    215218    if errorinfo:
    216         print colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red')
     219        print(colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red'))
    217220
    218221def colCat(_ctx, strg):
     
    241244    mach = vbox.createMachine("", name, [], kind, "")
    242245    mach.saveSettings()
    243     print "created machine with UUID", mach.id
     246    print("created machine with UUID", mach.id)
    244247    vbox.registerMachine(mach)
    245248    # update cache
     
    248251def removeVm(ctx, mach):
    249252    uuid = mach.id
    250     print "removing machine ", mach.name, "with UUID", uuid
     253    print("removing machine ", mach.name, "with UUID", uuid)
    251254    cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
    252255    disks = mach.unregister(ctx['global'].constants.CleanupMode_Full)
     
    254257        progress = mach.deleteConfig(disks)
    255258        if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
    256             print "Success!"
     259            print("Success!")
    257260        else:
    258261            reportError(ctx, progress)
     
    271274            try:
    272275                perf.setup(['*'], [mach], 10, 15)
    273             except Exception, e:
     276            except Exception as e:
    274277                printErr(ctx, e)
    275278                if g_fVerbose:
     
    324327        return
    325328    for metric in ctx['perf'].query(["*"], [mach]):
    326         print metric['name'], metric['values_as_string']
     329        print(metric['name'], metric['values_as_string'])
    327330
    328331def guestExec(ctx, machine, console, cmds):
    329     exec cmds
     332    exec(cmds)
    330333
    331334def printMouseEvent(_ctx, mev):
    332     print "Mouse : mode=%d x=%d y=%d z=%d w=%d buttons=%x" % (mev.mode, mev.x, mev.y, mev.z, mev.w, mev.buttons)
     335    print("Mouse : mode=%d x=%d y=%d z=%d w=%d buttons=%x" % (mev.mode, mev.x, mev.y, mev.z, mev.w, mev.buttons))
    333336
    334337def printKbdEvent(ctx, kev):
    335     print "Kbd: ", ctx['global'].getArray(kev, 'scancodes')
     338    print("Kbd: ", ctx['global'].getArray(kev, 'scancodes'))
    336339
    337340def printMultiTouchEvent(ctx, mtev):
    338     print "MultiTouch : contacts=%d time=%d" % (mtev.contactCount, mtev.scanTime)
     341    print("MultiTouch : contacts=%d time=%d" % (mtev.contactCount, mtev.scanTime))
    339342    xPositions = ctx['global'].getArray(mtev, 'xPositions')
    340343    yPositions = ctx['global'].getArray(mtev, 'yPositions')
     
    343346
    344347    for i in range(0, mtev.contactCount):
    345         print "  [%d] %d,%d %d %d" % (i, xPositions[i], yPositions[i], contactIds[i], contactFlags[i])
     348        print("  [%d] %d,%d %d %d" % (i, xPositions[i], yPositions[i], contactIds[i], contactFlags[i]))
    346349
    347350def monitorSource(ctx, eventSource, active, dur):
    348351    def handleEventImpl(event):
    349352        evtype = event.type
    350         print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype))
     353        print("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))
    351354        if evtype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:
    352355            scev = ctx['global'].queryInterface(event, 'IMachineStateChangedEvent')
    353356            if scev:
    354                 print "machine state event: mach=%s state=%s" % (scev.machineId, scev.state)
     357                print("machine state event: mach=%s state=%s" % (scev.machineId, scev.state))
    355358        elif  evtype == ctx['global'].constants.VBoxEventType_OnSnapshotTaken:
    356359            stev = ctx['global'].queryInterface(event, 'ISnapshotTakenEvent')
    357360            if stev:
    358                 print "snapshot taken event: mach=%s snap=%s" % (stev.machineId, stev.snapshotId)
     361                print("snapshot taken event: mach=%s snap=%s" % (stev.machineId, stev.snapshotId))
    359362        elif  evtype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:
    360363            gpcev = ctx['global'].queryInterface(event, 'IGuestPropertyChangedEvent')
    361364            if gpcev:
    362                 print "guest property change: name=%s value=%s" % (gpcev.name, gpcev.value)
     365                print("guest property change: name=%s value=%s" % (gpcev.name, gpcev.value))
    363366        elif  evtype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:
    364367            psev = ctx['global'].queryInterface(event, 'IMousePointerShapeChangedEvent')
     
    366369                shape = ctx['global'].getArray(psev, 'shape')
    367370                if shape is None:
    368                     print "pointer shape event - empty shape"
     371                    print("pointer shape event - empty shape")
    369372                else:
    370                     print "pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape))
     373                    print("pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape)))
    371374        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
    372375            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
     
    441444    def handleEventImpl(event):
    442445        evtype = event.type
    443         #print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype))
     446        #print("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))
    444447        if evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
    445448            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
     
    489492
    490493    header = demo.readline()
    491     print "Header is", header
     494    print("Header is", header)
    492495    basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)')
    493496    mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)')
     
    515518            if rtype == 'k':
    516519                codes = kre.findall(params)
    517                 #print "KBD:", codes
     520                #print("KBD:", codes)
    518521                kbd.putScancodes(codes)
    519522            elif rtype == 'm':
     
    523526                    if mdict['a'] == '1':
    524527                        # absolute
    525                         #print "MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b']
     528                        #print("MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b'])
    526529                        mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
    527530                    else:
    528                         #print "MR: ", mdict['x'], mdict['y'], mdict['b']
     531                        #print("MR: ", mdict['x'], mdict['y'], mdict['b'])
    529532                        mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
    530533
     
    559562        h = fbh
    560563
    561     print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f)
     564    print("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))
    562565    data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_RGBA)
    563566    size = (w, h)
     
    586589        h = fbh
    587590
    588     print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f)
     591    print("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))
    589592    data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_PNG)
    590593    pngfile = open(f, 'wb')
     
    594597def teleport(ctx, _session, console, args):
    595598    if args[0].find(":") == -1:
    596         print "Use host:port format for teleport target"
     599        print("Use host:port format for teleport target")
    597600        return
    598601    (host, port) = args[0].split(":")
     
    608611
    609612    port = int(port)
    610     print "Teleporting to %s:%d..." % (host, port)
     613    print("Teleporting to %s:%d..." % (host, port))
    611614    progress = console.teleport(host, port, passwd, maxDowntime)
    612615    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
    613         print "Success!"
     616        print("Success!")
    614617    else:
    615618        reportError(ctx, progress)
     
    632635    all_stats = ctx['const'].all_values('GuestStatisticType')
    633636    cpu = 0
    634     for s in all_stats.keys():
     637    for s in list(all_stats.keys()):
    635638        try:
    636639            val = guest.getStatistic( cpu, all_stats[s])
    637             print "%s: %d" % (s, val)
     640            print("%s: %d" % (s, val))
    638641        except:
    639642            # likely not implemented
     
    642645def plugCpu(_ctx, machine, _session, args):
    643646    cpu = int(args[0])
    644     print "Adding CPU %d..." % (cpu)
     647    print("Adding CPU %d..." % (cpu))
    645648    machine.hotPlugCPU(cpu)
    646649
    647650def unplugCpu(_ctx, machine, _session, args):
    648651    cpu = int(args[0])
    649     print "Removing CPU %d..." % (cpu)
     652    print("Removing CPU %d..." % (cpu))
    650653    machine.hotUnplugCPU(cpu)
    651654
     
    661664
    662665def printHostUsbDev(ctx, ud):
    663     print "  %s: %s (vendorId=%d productId=%d serial=%s) %s" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber, asEnumElem(ctx, 'USBDeviceState', ud.state))
     666    print("  %s: %s (vendorId=%d productId=%d serial=%s) %s" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber, asEnumElem(ctx, 'USBDeviceState', ud.state)))
    664667
    665668def printUsbDev(_ctx, ud):
    666     print "  %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id,  colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber)
     669    print("  %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id,  colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber))
    667670
    668671def printSf(ctx, sf):
    669     print "    name=%s host=%s %s %s" % (sf.name, colPath(ctx, sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
     672    print("    name=%s host=%s %s %s" % (sf.name, colPath(ctx, sf.hostPath), cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only")))
    670673
    671674def ginfo(ctx, console, _args):
    672675    guest = console.guest
    673676    if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None:
    674         print "Additions active, version %s" % (guest.additionsVersion)
    675         print "Support seamless: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless))
    676         print "Support graphics: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics))
    677         print "Balloon size: %d" % (guest.memoryBalloonSize)
    678         print "Statistic update interval: %d" % (guest.statisticsUpdateInterval)
    679     else:
    680         print "No additions"
     677        print("Additions active, version %s" % (guest.additionsVersion))
     678        print("Support seamless: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless)))
     679        print("Support graphics: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics)))
     680        print("Balloon size: %d" % (guest.memoryBalloonSize))
     681        print("Statistic update interval: %d" % (guest.statisticsUpdateInterval))
     682    else:
     683        print("No additions")
    681684    usbs = ctx['global'].getArray(console, 'USBDevices')
    682     print "Attached USB:"
     685    print("Attached USB:")
    683686    for ud in usbs:
    684687        printUsbDev(ctx, ud)
    685688    rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
    686     print "Remote USB:"
     689    print("Remote USB:")
    687690    for ud in rusbs:
    688691        printHostUsbDev(ctx, ud)
    689     print "Transient shared folders:"
     692    print("Transient shared folders:")
    690693    sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
    691694    for sf in sfs:
     
    698701        session = ctx['global'].getSessionObject(vbox)
    699702        mach.lockMachine(session, ctx['global'].constants.LockType_Shared)
    700     except Exception, e:
     703    except Exception as e:
    701704        printErr(ctx, "Session to '%s' not open: %s" % (mach.name, str(e)))
    702705        if g_fVerbose:
     
    704707        return
    705708    if session.state != ctx['const'].SessionState_Locked:
    706         print "Session to '%s' in wrong state: %s" % (mach.name, session.state)
     709        print("Session to '%s' in wrong state: %s" % (mach.name, session.state))
    707710        session.unlockMachine()
    708711        return
     
    710713    # in Webservices) functionality
    711714    if ctx['remote'] and cmd == 'some_local_only_command':
    712         print 'Trying to use local only functionality, ignored'
     715        print('Trying to use local only functionality, ignored')
    713716        session.unlockMachine()
    714717        return
     
    734737    except KeyboardInterrupt:
    735738        ctx['interrupt'] = True
    736     except Exception, e:
     739    except Exception as e:
    737740        printErr(ctx, e)
    738741        if g_fVerbose:
     
    747750    try:
    748751        cmd(ctx, mach, args)
    749     except Exception, e:
     752    except Exception as e:
    750753        save = False
    751754        printErr(ctx, e)
     
    755758        try:
    756759            mach.saveSettings()
    757         except Exception, e:
     760        except Exception as e:
    758761            printErr(ctx, e)
    759762            if g_fVerbose:
     
    767770    try:
    768771        cmd(ctx, mach, session.console, args)
    769     except Exception, e:
     772    except Exception as e:
    770773        save = False
    771774        printErr(ctx, e)
     
    777780
    778781def machById(ctx, uuid):
    779     try:
    780         mach = ctx['vb'].getMachine(uuid)
    781     except:
    782         mach = ctx['vb'].findMachine(uuid)
     782    mach = ctx['vb'].findMachine(uuid)
    783783    return mach
    784784
     
    899899def argsToMach(ctx, args):
    900900    if len(args) < 2:
    901         print "usage: %s [vmname|uuid]" % (args[0])
     901        print("usage: %s [vmname|uuid]" % (args[0]))
    902902        return None
    903903    uuid = args[1]
    904904    mach = machById(ctx, uuid)
    905905    if mach == None:
    906         print "Machine '%s' is unknown, use list command to find available machines" % (uuid)
     906        print("Machine '%s' is unknown, use list command to find available machines" % (uuid))
    907907    return mach
    908908
     
    912912    else:
    913913        spec = ""
    914     print "    %s: %s%s" % (colored(cmd, 'blue'), h, spec)
     914    print("    %s: %s%s" % (colored(cmd, 'blue'), h, spec))
    915915
    916916def helpCmd(_ctx, args):
    917917    if len(args) == 1:
    918         print "Help page:"
    919         names = commands.keys()
     918        print("Help page:")
     919        names = list(commands.keys())
    920920        names.sort()
    921921        for i in names:
     
    925925        c = commands.get(cmd)
    926926        if c == None:
    927             print "Command '%s' not known" % (cmd)
     927            print("Command '%s' not known" % (cmd))
    928928        else:
    929929            helpSingleCmd(cmd, c[0], c[2])
     
    932932def asEnumElem(ctx, enum, elem):
    933933    enumVals = ctx['const'].all_values(enum)
    934     for e in enumVals.keys():
     934    for e in list(enumVals.keys()):
    935935        if str(elem) == str(enumVals[e]):
    936936            return colored(e, 'green')
     
    948948            else:
    949949                tele = "    "
    950                 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" % (tele, colVm(ctx, mach.name), mach.id, asEnumElem(ctx, "MachineState", mach.state), asEnumElem(ctx, "SessionState", mach.sessionState))
    951         except Exception, e:
     950                print("%sMachine '%s' [%s], machineState=%s, sessionState=%s" % (tele, colVm(ctx, mach.name), mach.id, asEnumElem(ctx, "MachineState", mach.state), asEnumElem(ctx, "SessionState", mach.sessionState)))
     951        except Exception as e:
    952952            printErr(ctx, e)
    953953            if g_fVerbose:
     
    956956
    957957def infoCmd(ctx, args):
    958     if (len(args) < 2):
    959         print "usage: info [vmname|uuid]"
     958    if len(args) < 2:
     959        print("usage: info [vmname|uuid]")
    960960        return 0
    961961    mach = argsToMach(ctx, args)
     
    963963        return 0
    964964    vmos = ctx['vb'].getGuestOSType(mach.OSTypeId)
    965     print " One can use setvar <mach> <var> <value> to change variable, using name in []."
    966     print "  Name [name]: %s" % (colVm(ctx, mach.name))
    967     print "  Description [description]: %s" % (mach.description)
    968     print "  ID [n/a]: %s" % (mach.id)
    969     print "  OS Type [via OSTypeId]: %s" % (vmos.description)
    970     print "  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType)
    971     print
    972     print "  CPUs [CPUCount]: %d" % (mach.CPUCount)
    973     print "  RAM [memorySize]: %dM" % (mach.memorySize)
    974     print "  VRAM [VRAMSize]: %dM" % (mach.VRAMSize)
    975     print "  Monitors [monitorCount]: %d" % (mach.monitorCount)
    976     print "  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType)
    977     print
    978     print "  Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode)
    979     print "  Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState)
    980     print
     965    print(" One can use setvar <mach> <var> <value> to change variable, using name in [].")
     966    print("  Name [name]: %s" % (colVm(ctx, mach.name)))
     967    print("  Description [description]: %s" % (mach.description))
     968    print("  ID [n/a]: %s" % (mach.id))
     969    print("  OS Type [via OSTypeId]: %s" % (vmos.description))
     970    print("  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType))
     971    print()
     972    print("  CPUs [CPUCount]: %d" % (mach.CPUCount))
     973    print("  RAM [memorySize]: %dM" % (mach.memorySize))
     974    print("  VRAM [VRAMSize]: %dM" % (mach.VRAMSize))
     975    print("  Monitors [monitorCount]: %d" % (mach.monitorCount))
     976    print("  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType))
     977    print()
     978    print("  Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode))
     979    print("  Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState))
     980    print()
    981981    if mach.teleporterEnabled:
    982         print "  Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword)
    983         print
     982        print("  Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword))
     983        print()
    984984    bios = mach.BIOSSettings
    985     print "  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled))
    986     print "  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled))
     985    print("  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled)))
     986    print("  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled)))
    987987    hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
    988     print "  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled)
     988    print("  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled))
    989989    hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
    990     print "  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID)
     990    print("  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID))
    991991    hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
    992     print "  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging)
    993 
    994     print "  Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
    995     print "  Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
    996 
    997     print "  Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC))
    998     print "  HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled))
     992    print("  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging))
     993
     994    print("  Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled))
     995    print("  Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled))
     996
     997    print("  Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC)))
     998    print("  HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled)))
    999999    if mach.audioAdapter.enabled:
    1000         print "  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType",  mach.audioAdapter.audioDriver))
    1001     print "  CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled))
    1002 
    1003     print "  Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx, "KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType)
    1004     print "  Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx, "PointingHIDType", mach.pointingHIDType), mach.pointingHIDType)
    1005     print "  Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
     1000        print("  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType",  mach.audioAdapter.audioDriver)))
     1001    print("  CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled)))
     1002
     1003    print("  Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx, "KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType))
     1004    print("  Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx, "PointingHIDType", mach.pointingHIDType), mach.pointingHIDType))
     1005    print("  Last changed [n/a]: " + time.asctime(time.localtime(mach.lastStateChange/1000)))
    10061006    # OSE has no VRDE
    10071007    try:
    1008         print "  VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled))
     1008        print("  VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled)))
    10091009    except:
    10101010        pass
    10111011
    1012     print
    1013     print colCat(ctx, "  USB Controllers:")
     1012    print()
     1013    print(colCat(ctx, "  USB Controllers:"))
    10141014    for oUsbCtrl in ctx['global'].getArray(mach, 'USBControllers'):
    1015         print "    '%s': type %s  standard: %#x" \
    1016             % (oUsbCtrl.name, asEnumElem(ctx, "USBControllerType", oUsbCtrl.type), oUsbCtrl.USBStandard);
    1017 
    1018     print
    1019     print colCat(ctx, "  I/O subsystem info:")
    1020     print "   Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled))
    1021     print "   Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize)
     1015        print("    '%s': type %s  standard: %#x" \
     1016            % (oUsbCtrl.name, asEnumElem(ctx, "USBControllerType", oUsbCtrl.type), oUsbCtrl.USBStandard))
     1017
     1018    print()
     1019    print(colCat(ctx, "  I/O subsystem info:"))
     1020    print("   Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled)))
     1021    print("   Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize))
    10221022
    10231023    controllers = ctx['global'].getArray(mach, 'storageControllers')
    10241024    if controllers:
    1025         print
    1026         print colCat(ctx, "  Storage Controllers:")
     1025        print()
     1026        print(colCat(ctx, "  Storage Controllers:"))
    10271027    for controller in controllers:
    1028         print "    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx, "StorageControllerType", controller.controllerType))
     1028        print("    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx, "StorageControllerType", controller.controllerType)))
    10291029
    10301030    attaches = ctx['global'].getArray(mach, 'mediumAttachments')
    10311031    if attaches:
    1032         print
    1033         print colCat(ctx, "  Media:")
     1032        print()
     1033        print(colCat(ctx, "  Media:"))
    10341034    for a in attaches:
    1035         print "   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type)
     1035        print("   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type))
    10361036        medium = a.medium
    10371037        if a.type == ctx['global'].constants.DeviceType_HardDisk:
    1038             print "   HDD:"
    1039             print "    Id: %s" % (medium.id)
    1040             print "    Location: %s" % (colPath(ctx, medium.location))
    1041             print "    Name: %s" % (medium.name)
    1042             print "    Format: %s" % (medium.format)
     1038            print("   HDD:")
     1039            print("    Id: %s" % (medium.id))
     1040            print("    Location: %s" % (colPath(ctx, medium.location)))
     1041            print("    Name: %s" % (medium.name))
     1042            print("    Format: %s" % (medium.format))
    10431043
    10441044        if a.type == ctx['global'].constants.DeviceType_DVD:
    1045             print "   DVD:"
     1045            print("   DVD:")
    10461046            if medium:
    1047                 print "    Id: %s" % (medium.id)
    1048                 print "    Name: %s" % (medium.name)
     1047                print("    Id: %s" % (medium.id))
     1048                print("    Name: %s" % (medium.name))
    10491049                if medium.hostDrive:
    1050                     print "    Host DVD %s" % (colPath(ctx, medium.location))
     1050                    print("    Host DVD %s" % (colPath(ctx, medium.location)))
    10511051                    if a.passthrough:
    1052                         print "    [passthrough mode]"
     1052                        print("    [passthrough mode]")
    10531053                else:
    1054                     print "    Virtual image at %s" % (colPath(ctx, medium.location))
    1055                     print "    Size: %s" % (medium.size)
     1054                    print("    Virtual image at %s" % (colPath(ctx, medium.location)))
     1055                    print("    Size: %s" % (medium.size))
    10561056
    10571057        if a.type == ctx['global'].constants.DeviceType_Floppy:
    1058             print "   Floppy:"
     1058            print("   Floppy:")
    10591059            if medium:
    1060                 print "    Id: %s" % (medium.id)
    1061                 print "    Name: %s" % (medium.name)
     1060                print("    Id: %s" % (medium.id))
     1061                print("    Name: %s" % (medium.name))
    10621062                if medium.hostDrive:
    1063                     print "    Host floppy %s" % (colPath(ctx, medium.location))
     1063                    print("    Host floppy %s" % (colPath(ctx, medium.location)))
    10641064                else:
    1065                     print "    Virtual image at %s" % (colPath(ctx, medium.location))
    1066                     print "    Size: %s" % (medium.size)
    1067 
    1068     print
    1069     print colCat(ctx, "  Shared folders:")
     1065                    print("    Virtual image at %s" % (colPath(ctx, medium.location)))
     1066                    print("    Size: %s" % (medium.size))
     1067
     1068    print()
     1069    print(colCat(ctx, "  Shared folders:"))
    10701070    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
    10711071        printSf(ctx, sf)
     
    10751075def startCmd(ctx, args):
    10761076    if len(args) < 2:
    1077         print "usage: start name <frontend>"
     1077        print("usage: start name <frontend>")
    10781078        return 0
    10791079    mach = argsToMach(ctx, args)
     
    10881088
    10891089def createVmCmd(ctx, args):
    1090     if (len(args) != 3):
    1091         print "usage: createvm name ostype"
     1090    if len(args) != 3:
     1091        print("usage: createvm name ostype")
    10921092        return 0
    10931093    name = args[1]
     
    10961096        ctx['vb'].getGuestOSType(oskind)
    10971097    except Exception:
    1098         print 'Unknown OS type:', oskind
     1098        print('Unknown OS type:', oskind)
    10991099        return 0
    11001100    createVm(ctx, name, oskind)
     
    11021102
    11031103def ginfoCmd(ctx, args):
    1104     if (len(args) < 2):
    1105         print "usage: ginfo [vmname|uuid]"
     1104    if len(args) < 2:
     1105        print("usage: ginfo [vmname|uuid]")
    11061106        return 0
    11071107    mach = argsToMach(ctx, args)
     
    11131113def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None):
    11141114    if len(args) < 1:
    1115         print "exec in guest needs at least program name"
     1115        print("exec in guest needs at least program name")
    11161116        return
    11171117    guest = console.guest
     
    11191119    # shall contain program name as argv[0]
    11201120    gargs = args
    1121     print "executing %s with args %s as %s" % (args[0], gargs, user)
     1121    print("executing %s with args %s as %s" % (args[0], gargs, user))
    11221122    flags = 0
    11231123    if inputPipe is not None:
    11241124        flags = 1 # set WaitForProcessStartOnly
    1125     print args[0]
     1125    print(args[0])
    11261126    process = guestSession.processCreate(args[0], gargs, env, [], tmo)
    1127     print "executed with pid %d" % (process.PID)
     1127    print("executed with pid %d" % (process.PID))
    11281128    if pid != 0:
    11291129        try:
     
    11611161
    11621162        except KeyboardInterrupt:
    1163             print "Interrupted."
     1163            print("Interrupted.")
    11641164            ctx['interrupt'] = True
    11651165            if progress.cancelable:
    11661166                progress.cancel()
    11671167        (_reason, code, _flags) = guest.getProcessStatus(pid)
    1168         print "Exit code: %d" % (code)
     1168        print("Exit code: %d" % (code))
    11691169        return 0
    11701170    else:
     
    11751175    dst = args[1]
    11761176    flags = 0
    1177     print "Copying host %s to guest %s" % (src, dst)
     1177    print("Copying host %s to guest %s" % (src, dst))
    11781178    progress = console.guest.copyToGuest(src, dst, user, passwd, flags)
    11791179    progressBar(ctx, progress)
     
    11961196    user = getpass.getuser()
    11971197    user_inp = nh_raw_input("User (%s): " % (user))
    1198     if len (user_inp) > 0:
     1198    if len(user_inp) > 0:
    11991199        user = user_inp
    12001200    passwd = getpass.getpass()
     
    12031203
    12041204def gexecCmd(ctx, args):
    1205     if (len(args) < 2):
    1206         print "usage: gexec [vmname|uuid] command args"
     1205    if len(args) < 2:
     1206        print("usage: gexec [vmname|uuid] command args")
    12071207        return 0
    12081208    mach = argsToMach(ctx, args)
     
    12171217
    12181218def gcopyCmd(ctx, args):
    1219     if (len(args) < 2):
    1220         print "usage: gcopy [vmname|uuid] host_path guest_path"
     1219    if len(args) < 2:
     1220        print("usage: gcopy [vmname|uuid] host_path guest_path")
    12211221        return 0
    12221222    mach = argsToMach(ctx, args)
     
    12361236
    12371237def gpipeCmd(ctx, args):
    1238     if (len(args) < 4):
    1239         print "usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'"
     1238    if len(args) < 4:
     1239        print("usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'")
    12401240        return 0
    12411241    mach = argsToMach(ctx, args)
     
    13091309
    13101310def guestCmd(ctx, args):
    1311     if (len(args) < 3):
    1312         print "usage: guest name commands"
     1311    if len(args) < 3:
     1312        print("usage: guest name commands")
    13131313        return 0
    13141314    mach = argsToMach(ctx, args)
     
    13221322
    13231323def screenshotCmd(ctx, args):
    1324     if (len(args) < 2):
    1325         print "usage: screenshot vm <file> <width> <height> <monitor>"
     1324    if len(args) < 2:
     1325        print("usage: screenshot vm <file> <width> <height> <monitor>")
    13261326        return 0
    13271327    mach = argsToMach(ctx, args)
     
    13321332
    13331333def teleportCmd(ctx, args):
    1334     if (len(args) < 3):
    1335         print "usage: teleport name host:port <password>"
     1334    if len(args) < 3:
     1335        print("usage: teleport name host:port <password>")
    13361336        return 0
    13371337    mach = argsToMach(ctx, args)
     
    13511351
    13521352def openportalCmd(ctx, args):
    1353     if (len(args) < 3):
    1354         print "usage: openportal name port <password>"
     1353    if len(args) < 3:
     1354        print("usage: openportal name port <password>")
    13551355        return 0
    13561356    mach = argsToMach(ctx, args)
     
    13581358        return 0
    13591359    port = int(args[2])
    1360     if (len(args) > 3):
     1360    if len(args) > 3:
    13611361        passwd = args[3]
    13621362    else:
     
    13681368
    13691369def closeportalCmd(ctx, args):
    1370     if (len(args) < 2):
    1371         print "usage: closeportal name"
     1370    if len(args) < 2:
     1371        print("usage: closeportal name")
    13721372        return 0
    13731373    mach = argsToMach(ctx, args)
     
    13791379
    13801380def gueststatsCmd(ctx, args):
    1381     if (len(args) < 2):
    1382         print "usage: gueststats name <check interval>"
     1381    if len(args) < 2:
     1382        print("usage: gueststats name <check interval>")
    13831383        return 0
    13841384    mach = argsToMach(ctx, args)
     
    13921392    cpu = args[1]
    13931393    if plug:
    1394         print "Adding CPU %d..." % (cpu)
     1394        print("Adding CPU %d..." % (cpu))
    13951395        mach.hotPlugCPU(cpu)
    13961396    else:
    1397         print "Removing CPU %d..." % (cpu)
     1397        print("Removing CPU %d..." % (cpu))
    13981398        mach.hotUnplugCPU(cpu)
    13991399
    14001400def plugcpuCmd(ctx, args):
    1401     if (len(args) < 2):
    1402         print "usage: plugcpu name cpuid"
     1401    if len(args) < 2:
     1402        print("usage: plugcpu name cpuid")
    14031403        return 0
    14041404    mach = argsToMach(ctx, args)
     
    14131413
    14141414def unplugcpuCmd(ctx, args):
    1415     if (len(args) < 2):
    1416         print "usage: unplugcpu name cpuid"
     1415    if len(args) < 2:
     1416        print("usage: unplugcpu name cpuid")
    14171417        return 0
    14181418    mach = argsToMach(ctx, args)
     
    14281428def setvar(_ctx, _mach, args):
    14291429    expr = 'mach.'+args[0]+' = '+args[1]
    1430     print "Executing", expr
    1431     exec expr
     1430    print("Executing", expr)
     1431    exec(expr)
    14321432
    14331433def setvarCmd(ctx, args):
    1434     if (len(args) < 4):
    1435         print "usage: setvar [vmname|uuid] expr value"
     1434    if len(args) < 4:
     1435        print("usage: setvar [vmname|uuid] expr value")
    14361436        return 0
    14371437    mach = argsToMach(ctx, args)
     
    14441444    key = args[0]
    14451445    value = args[1]
    1446     print "%s: setting %s to %s" % (mach.name, key, value if value else None)
     1446    print("%s: setting %s to %s" % (mach.name, key, value if value else None))
    14471447    mach.setExtraData(key, value)
    14481448
    14491449def setExtraDataCmd(ctx, args):
    1450     if (len(args) < 3):
    1451         print "usage: setextra [vmname|uuid|global] key <value>"
     1450    if len(args) < 3:
     1451        print("usage: setextra [vmname|uuid|global] key <value>")
    14521452        return 0
    14531453    key = args[2]
     
    14671467
    14681468def printExtraKey(obj, key, value):
    1469     print "%s: '%s' = '%s'" % (obj, key, value)
     1469    print("%s: '%s' = '%s'" % (obj, key, value))
    14701470
    14711471def getExtraDataCmd(ctx, args):
    1472     if (len(args) < 2):
    1473         print "usage: getextra [vmname|uuid|global] <key>"
     1472    if len(args) < 2:
     1473        print("usage: getextra [vmname|uuid|global] <key>")
    14741474        return 0
    14751475    if len(args) == 3:
     
    14981498
    14991499def aliasCmd(ctx, args):
    1500     if (len(args) == 3):
     1500    if len(args) == 3:
    15011501        aliases[args[1]] = args[2]
    15021502        return 0
    15031503
    1504     for (key, value) in aliases.items():
    1505         print "'%s' is an alias for '%s'" % (key, value)
     1504    for (key, value) in list(aliases.items()):
     1505        print("'%s' is an alias for '%s'" % (key, value))
    15061506    return 0
    15071507
    15081508def verboseCmd(ctx, args):
    15091509    global g_fVerbose
    1510     if (len(args) > 1):
     1510    if len(args) > 1:
    15111511        g_fVerbose = (args[1]=='on')
    15121512    else:
     
    15161516def colorsCmd(ctx, args):
    15171517    global g_fHasColors
    1518     if (len(args) > 1):
     1518    if len(args) > 1:
    15191519        g_fHasColors = (args[1] == 'on')
    15201520    else:
     
    15251525    vbox = ctx['vb']
    15261526    try:
    1527         print "VirtualBox version %s" % (colored(vbox.version, 'blue'))
    1528     except Exception, e:
     1527        print("VirtualBox version %s" % (colored(vbox.version, 'blue')))
     1528    except Exception as e:
    15291529        printErr(ctx, e)
    15301530        if g_fVerbose:
    15311531            traceback.print_exc()
    15321532    props = vbox.systemProperties
    1533     print "Machines: %s" % (colPath(ctx, props.defaultMachineFolder))
    1534 
    1535     #print "Global shared folders:"
     1533    print("Machines: %s" % (colPath(ctx, props.defaultMachineFolder)))
     1534
     1535    #print("Global shared folders:")
    15361536    #for ud in ctx['global'].getArray(vbox, 'sharedFolders'):
    15371537    #    printSf(ctx, sf)
    15381538    host = vbox.host
    15391539    cnt = host.processorCount
    1540     print colCat(ctx, "Processors:")
    1541     print "  available/online: %d/%d " % (cnt, host.processorOnlineCount)
     1540    print(colCat(ctx, "Processors:"))
     1541    print("  available/online: %d/%d " % (cnt, host.processorOnlineCount))
    15421542    for i in range(0, cnt):
    1543         print "  processor #%d speed: %dMHz %s" % (i, host.getProcessorSpeed(i), host.getProcessorDescription(i))
    1544 
    1545     print colCat(ctx, "RAM:")
    1546     print "  %dM (free %dM)" % (host.memorySize, host.memoryAvailable)
    1547     print colCat(ctx, "OS:")
    1548     print "  %s (%s)" % (host.operatingSystem, host.OSVersion)
     1543        print("  processor #%d speed: %dMHz %s" % (i, host.getProcessorSpeed(i), host.getProcessorDescription(i)))
     1544
     1545    print(colCat(ctx, "RAM:"))
     1546    print("  %dM (free %dM)" % (host.memorySize, host.memoryAvailable))
     1547    print(colCat(ctx, "OS:"))
     1548    print("  %s (%s)" % (host.operatingSystem, host.OSVersion))
    15491549    if host.acceleration3DAvailable:
    1550         print colCat(ctx, "3D acceleration available")
    1551     else:
    1552         print colCat(ctx, "3D acceleration NOT available")
    1553 
    1554     print colCat(ctx, "Network interfaces:")
     1550        print(colCat(ctx, "3D acceleration available"))
     1551    else:
     1552        print(colCat(ctx, "3D acceleration NOT available"))
     1553
     1554    print(colCat(ctx, "Network interfaces:"))
    15551555    for ni in ctx['global'].getArray(host, 'networkInterfaces'):
    1556         print "  %s (%s)" % (ni.name, ni.IPAddress)
    1557 
    1558     print colCat(ctx, "DVD drives:")
     1556        print("  %s (%s)" % (ni.name, ni.IPAddress))
     1557
     1558    print(colCat(ctx, "DVD drives:"))
    15591559    for dd in ctx['global'].getArray(host, 'DVDDrives'):
    1560         print "  %s - %s" % (dd.name, dd.description)
    1561 
    1562     print colCat(ctx, "Floppy drives:")
     1560        print("  %s - %s" % (dd.name, dd.description))
     1561
     1562    print(colCat(ctx, "Floppy drives:"))
    15631563    for dd in ctx['global'].getArray(host, 'floppyDrives'):
    1564         print "  %s - %s" % (dd.name, dd.description)
    1565 
    1566     print colCat(ctx, "USB devices:")
     1564        print("  %s - %s" % (dd.name, dd.description))
     1565
     1566    print(colCat(ctx, "USB devices:"))
    15671567    for ud in ctx['global'].getArray(host, 'USBDevices'):
    15681568        printHostUsbDev(ctx, ud)
     
    15701570    if ctx['perf']:
    15711571        for metric in ctx['perf'].query(["*"], [host]):
    1572             print metric['name'], metric['values_as_string']
     1572            print(metric['name'], metric['values_as_string'])
    15731573
    15741574    return 0
    15751575
    15761576def monitorGuestCmd(ctx, args):
    1577     if (len(args) < 2):
    1578         print "usage: monitorGuest name (duration)"
     1577    if len(args) < 2:
     1578        print("usage: monitorGuest name (duration)")
    15791579        return 0
    15801580    mach = argsToMach(ctx, args)
     
    15891589
    15901590def monitorGuestKbdCmd(ctx, args):
    1591     if (len(args) < 2):
    1592         print "usage: monitorGuestKbd name (duration)"
     1591    if len(args) < 2:
     1592        print("usage: monitorGuestKbd name (duration)")
    15931593        return 0
    15941594    mach = argsToMach(ctx, args)
     
    16031603
    16041604def monitorGuestMouseCmd(ctx, args):
    1605     if (len(args) < 2):
    1606         print "usage: monitorGuestMouse name (duration)"
     1605    if len(args) < 2:
     1606        print("usage: monitorGuestMouse name (duration)")
    16071607        return 0
    16081608    mach = argsToMach(ctx, args)
     
    16171617
    16181618def monitorGuestMultiTouchCmd(ctx, args):
    1619     if (len(args) < 2):
    1620         print "usage: monitorGuestMultiTouch name (duration)"
     1619    if len(args) < 2:
     1620        print("usage: monitorGuestMultiTouch name (duration)")
    16211621        return 0
    16221622    mach = argsToMach(ctx, args)
     
    16311631
    16321632def monitorVBoxCmd(ctx, args):
    1633     if (len(args) > 2):
    1634         print "usage: monitorVBox (duration)"
     1633    if len(args) > 2:
     1634        print("usage: monitorVBox (duration)")
    16351635        return 0
    16361636    dur = 5
     
    16591659
    16601660def portForwardCmd(ctx, args):
    1661     if (len(args) != 5):
    1662         print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
     1661    if len(args) != 5:
     1662        print("usage: portForward <vm> <adapter> <hostPort> <guestPort>")
    16631663        return 0
    16641664    mach = argsToMach(ctx, args)
     
    16901690
    16911691def showLogCmd(ctx, args):
    1692     if (len(args) < 2):
    1693         print "usage: showLog vm <num>"
     1692    if len(args) < 2:
     1693        print("usage: showLog vm <num>")
    16941694        return 0
    16951695    mach = argsToMach(ctx, args)
     
    16981698
    16991699    log = 0
    1700     if (len(args) > 2):
     1700    if len(args) > 2:
    17011701        log = args[2]
    17021702
     
    17041704    while True:
    17051705        data = mach.readLog(log, uOffset, 4096)
    1706         if (len(data) == 0):
     1706        if len(data) == 0:
    17071707            break
    17081708        # print adds either NL or space to chunks not ending with a NL
     
    17131713
    17141714def findLogCmd(ctx, args):
    1715     if (len(args) < 3):
    1716         print "usage: findLog vm pattern <num>"
     1715    if len(args) < 3:
     1716        print("usage: findLog vm pattern <num>")
    17171717        return 0
    17181718    mach = argsToMach(ctx, args)
     
    17211721
    17221722    log = 0
    1723     if (len(args) > 3):
     1723    if len(args) > 3:
    17241724        log = args[3]
    17251725
     
    17291729        # to reduce line splits on buffer boundary
    17301730        data = mach.readLog(log, uOffset, 512*1024)
    1731         if (len(data) == 0):
     1731        if len(data) == 0:
    17321732            break
    17331733        d = str(data).split("\n")
     
    17371737                for mt in match:
    17381738                    s = s.replace(mt, colored(mt, 'red'))
    1739                 print s
     1739                print(s)
    17401740        uOffset += len(data)
    17411741
     
    17441744
    17451745def findAssertCmd(ctx, args):
    1746     if (len(args) < 2):
    1747         print "usage: findAssert vm <num>"
     1746    if len(args) < 2:
     1747        print("usage: findAssert vm <num>")
    17481748        return 0
    17491749    mach = argsToMach(ctx, args)
     
    17521752
    17531753    log = 0
    1754     if (len(args) > 2):
     1754    if len(args) > 2:
    17551755        log = args[2]
    17561756
     
    17621762        # to reduce line splits on buffer boundary
    17631763        data = mach.readLog(log, uOffset, 512*1024)
    1764         if (len(data) == 0):
     1764        if len(data) == 0:
    17651765            break
    17661766        d = str(data).split("\n")
    17671767        for s in d:
    17681768            if active:
    1769                 print s
     1769                print(s)
    17701770                if context == 0:
    17711771                    active = False
     
    17771777                active = True
    17781778                context = 50
    1779                 print s
     1779                print(s)
    17801780        uOffset += len(data)
    17811781
     
    17851785    expr = ' '.join(args[1:])
    17861786    try:
    1787         exec expr
    1788     except Exception, e:
     1787        exec(expr)
     1788    except Exception as e:
    17891789        printErr(ctx, e)
    17901790        if g_fVerbose:
     
    17991799
    18001800def runScriptCmd(ctx, args):
    1801     if (len(args) != 2):
    1802         print "usage: runScript <script>"
     1801    if len(args) != 2:
     1802        print("usage: runScript <script>")
    18031803        return 0
    18041804    try:
    18051805        lf = open(args[1], 'r')
    1806     except IOError, e:
    1807         print "cannot open:", args[1], ":", e
     1806    except IOError as e:
     1807        print("cannot open:", args[1], ":", e)
    18081808        return 0
    18091809
     
    18191819                break
    18201820
    1821     except Exception, e:
     1821    except Exception as e:
    18221822        printErr(ctx, e)
    18231823        if g_fVerbose:
     
    18271827
    18281828def sleepCmd(ctx, args):
    1829     if (len(args) != 2):
    1830         print "usage: sleep <secs>"
     1829    if len(args) != 2:
     1830        print("usage: sleep <secs>")
    18311831        return 0
    18321832
     
    18401840
    18411841def shellCmd(ctx, args):
    1842     if (len(args) < 2):
    1843         print "usage: shell <commands>"
     1842    if len(args) < 2:
     1843        print("usage: shell <commands>")
    18441844        return 0
    18451845    cmd = ' '.join(args[1:])
     
    18541854
    18551855def connectCmd(ctx, args):
    1856     if (len(args) > 4):
    1857         print "usage: connect url <username> <passwd>"
     1856    if len(args) > 4:
     1857        print("usage: connect url <username> <passwd>")
    18581858        return 0
    18591859
    18601860    if ctx['vb'] is not None:
    1861         print "Already connected, disconnect first..."
    1862         return 0
    1863 
    1864     if (len(args) > 1):
     1861        print("Already connected, disconnect first...")
     1862        return 0
     1863
     1864    if len(args) > 1:
    18651865        url = args[1]
    18661866    else:
    18671867        url = None
    18681868
    1869     if (len(args) > 2):
     1869    if len(args) > 2:
    18701870        user = args[2]
    18711871    else:
    18721872        user = ""
    18731873
    1874     if (len(args) > 3):
     1874    if len(args) > 3:
    18751875        passwd = args[3]
    18761876    else:
     
    18811881    ctx['vb'] = vbox
    18821882    try:
    1883         print "Running VirtualBox version %s" % (vbox.version)
    1884     except Exception, e:
     1883        print("Running VirtualBox version %s" % (vbox.version))
     1884    except Exception as e:
    18851885        printErr(ctx, e)
    18861886        if g_fVerbose:
     
    18901890
    18911891def disconnectCmd(ctx, args):
    1892     if (len(args) != 1):
    1893         print "usage: disconnect"
     1892    if len(args) != 1:
     1893        print("usage: disconnect")
    18941894        return 0
    18951895
    18961896    if ctx['vb'] is None:
    1897         print "Not connected yet."
     1897        print("Not connected yet.")
    18981898        return 0
    18991899
     
    19091909def reconnectCmd(ctx, args):
    19101910    if ctx['wsinfo'] is None:
    1911         print "Never connected..."
     1911        print("Never connected...")
    19121912        return 0
    19131913
     
    19201920    ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
    19211921    try:
    1922         print "Running VirtualBox version %s" % (ctx['vb'].version)
    1923     except Exception, e:
     1922        print("Running VirtualBox version %s" % (ctx['vb'].version))
     1923    except Exception as e:
    19241924        printErr(ctx, e)
    19251925        if g_fVerbose:
     
    19291929def exportVMCmd(ctx, args):
    19301930    if len(args) < 3:
    1931         print "usage: exportVm <machine> <path> <format> <license>"
     1931        print("usage: exportVm <machine> <path> <format> <license>")
    19321932        return 0
    19331933    mach = argsToMach(ctx, args)
     
    19351935        return 0
    19361936    path = args[2]
    1937     if (len(args) > 3):
     1937    if len(args) > 3:
    19381938        fmt = args[3]
    19391939    else:
    19401940        fmt = "ovf-1.0"
    1941     if (len(args) > 4):
     1941    if len(args) > 4:
    19421942        lic = args[4]
    19431943    else:
     
    19491949    progress = app.write(fmt, path)
    19501950    if (progressBar(ctx, progress) and int(progress.resultCode) == 0):
    1951         print "Exported to %s in format %s" % (path, fmt)
     1951        print("Exported to %s in format %s" % (path, fmt))
    19521952    else:
    19531953        reportError(ctx, progress)
     
    20532053    extCode = extScancodes.get(ch, [])
    20542054    if len(extCode) == 0:
    2055         print "bad ext", ch
     2055        print("bad ext", ch)
    20562056    return extCode
    20572057
     
    21252125def typeGuestCmd(ctx, args):
    21262126    if len(args) < 3:
    2127         print "usage: typeGuest <machine> <text> <charDelay>"
     2127        print("usage: typeGuest <machine> <text> <charDelay>")
    21282128        return 0
    21292129    mach = argsToMach(ctx, args)
     
    21612161        verbose = False
    21622162    hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
    2163     print colCat(ctx, "Hard disks:")
     2163    print(colCat(ctx, "Hard disks:"))
    21642164    for hdd in hdds:
    21652165        if hdd.state != ctx['global'].constants.MediumState_Created:
    21662166            hdd.refreshState()
    2167         print "   %s (%s)%s %s [logical %s]" % (colPath(ctx, hdd.location), hdd.format, optId(verbose, hdd.id), colSizeM(ctx, asSize(hdd.size, True)), colSizeM(ctx, asSize(hdd.logicalSize, True)))
     2167        print("   %s (%s)%s %s [logical %s]" % (colPath(ctx, hdd.location), hdd.format, optId(verbose, hdd.id), colSizeM(ctx, asSize(hdd.size, True)), colSizeM(ctx, asSize(hdd.logicalSize, True))))
    21682168
    21692169    dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
    2170     print colCat(ctx, "CD/DVD disks:")
     2170    print(colCat(ctx, "CD/DVD disks:"))
    21712171    for dvd in dvds:
    21722172        if dvd.state != ctx['global'].constants.MediumState_Created:
    21732173            dvd.refreshState()
    2174         print "   %s (%s)%s %s" % (colPath(ctx, dvd.location), dvd.format, optId(verbose, dvd.id), colSizeM(ctx, asSize(dvd.size, True)))
     2174        print("   %s (%s)%s %s" % (colPath(ctx, dvd.location), dvd.format, optId(verbose, dvd.id), colSizeM(ctx, asSize(dvd.size, True))))
    21752175
    21762176    floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
    2177     print colCat(ctx, "Floppy disks:")
     2177    print(colCat(ctx, "Floppy disks:"))
    21782178    for floppy in floppys:
    21792179        if floppy.state != ctx['global'].constants.MediumState_Created:
    21802180            floppy.refreshState()
    2181         print "   %s (%s)%s %s" % (colPath(ctx, floppy.location), floppy.format, optId(verbose, floppy.id), colSizeM(ctx, asSize(floppy.size, True)))
     2181        print("   %s (%s)%s %s" % (colPath(ctx, floppy.location), floppy.format, optId(verbose, floppy.id), colSizeM(ctx, asSize(floppy.size, True))))
    21822182
    21832183    return 0
    21842184
    21852185def listUsbCmd(ctx, args):
    2186     if (len(args) > 1):
    2187         print "usage: listUsb"
     2186    if len(args) > 1:
     2187        print("usage: listUsb")
    21882188        return 0
    21892189
     
    22022202
    22032203def createHddCmd(ctx, args):
    2204     if (len(args) < 3):
    2205         print "usage: createHdd sizeM location type"
     2204    if len(args) < 3:
     2205        print("usage: createHdd sizeM location type")
    22062206        return 0
    22072207
     
    22162216    progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))
    22172217    if progressBar(ctx,progress) and hdd.id:
    2218         print "created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id)
    2219     else:
    2220        print "cannot create disk (file %s exist?)" % (loc)
     2218        print("created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id))
     2219    else:
     2220       print("cannot create disk (file %s exist?)" % (loc))
    22212221       reportError(ctx,progress)
    22222222       return 0
     
    22252225
    22262226def registerHddCmd(ctx, args):
    2227     if (len(args) < 2):
    2228         print "usage: registerHdd location"
     2227    if len(args) < 2:
     2228        print("usage: registerHdd location")
    22292229        return 0
    22302230
     
    22362236    parentId = ""
    22372237    hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    2238     print "registered HDD as %s" % (hdd.id)
     2238    print("registered HDD as %s" % (hdd.id))
    22392239    return 0
    22402240
     
    22442244
    22452245def attachHddCmd(ctx, args):
    2246     if (len(args) < 3):
    2247         print "usage: attachHdd vm hdd controller port:slot"
     2246    if len(args) < 3:
     2247        print("usage: attachHdd vm hdd controller port:slot")
    22482248        return 0
    22492249
     
    22562256        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    22572257    except:
    2258         print "no HDD with path %s registered" % (loc)
     2258        print("no HDD with path %s registered" % (loc))
    22592259        return 0
    22602260    if len(args) > 3:
     
    22792279
    22802280def detachHddCmd(ctx, args):
    2281     if (len(args) < 3):
    2282         print "usage: detachHdd vm hdd"
     2281    if len(args) < 3:
     2282        print("usage: detachHdd vm hdd")
    22832283        return 0
    22842284
     
    22912291        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    22922292    except:
    2293         print "no HDD with path %s registered" % (loc)
     2293        print("no HDD with path %s registered" % (loc))
    22942294        return 0
    22952295
     
    22982298
    22992299def unregisterHddCmd(ctx, args):
    2300     if (len(args) < 2):
    2301         print "usage: unregisterHdd path <vmunreg>"
     2300    if len(args) < 2:
     2301        print("usage: unregisterHdd path <vmunreg>")
    23022302        return 0
    23032303
    23042304    vbox = ctx['vb']
    23052305    loc = args[1]
    2306     if (len(args) > 2):
     2306    if len(args) > 2:
    23072307        vmunreg = int(args[2])
    23082308    else:
     
    23112311        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    23122312    except:
    2313         print "no HDD with path %s registered" % (loc)
     2313        print("no HDD with path %s registered" % (loc))
    23142314        return 0
    23152315
     
    23182318        try:
    23192319            for mach in machs:
    2320                 print "Trying to detach from %s" % (mach)
     2320                print("Trying to detach from %s" % (mach))
    23212321                detachMedium(ctx, mach, hdd)
    2322         except Exception, e:
    2323             print 'failed: ', e
     2322        except Exception as e:
     2323            print('failed: ', e)
    23242324            return 0
    23252325    hdd.close()
     
    23272327
    23282328def removeHddCmd(ctx, args):
    2329     if (len(args) != 2):
    2330         print "usage: removeHdd path"
     2329    if len(args) != 2:
     2330        print("usage: removeHdd path")
    23312331        return 0
    23322332
     
    23362336        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False)
    23372337    except:
    2338         print "no HDD with path %s registered" % (loc)
     2338        print("no HDD with path %s registered" % (loc))
    23392339        return 0
    23402340
     
    23452345
    23462346def registerIsoCmd(ctx, args):
    2347     if (len(args) < 2):
    2348         print "usage: registerIso location"
     2347    if len(args) < 2:
     2348        print("usage: registerIso location")
    23492349        return 0
    23502350
     
    23522352    loc = args[1]
    23532353    iso = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    2354     print "registered ISO as %s" % (iso.id)
     2354    print("registered ISO as %s" % (iso.id))
    23552355    return 0
    23562356
    23572357def unregisterIsoCmd(ctx, args):
    2358     if (len(args) != 2):
    2359         print "usage: unregisterIso path"
     2358    if len(args) != 2:
     2359        print("usage: unregisterIso path")
    23602360        return 0
    23612361
     
    23652365        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    23662366    except:
    2367         print "no DVD with path %s registered" % (loc)
     2367        print("no DVD with path %s registered" % (loc))
    23682368        return 0
    23692369
    23702370    progress = dvd.close()
    2371     print "Unregistered ISO at %s" % (colPath(ctx, loc))
     2371    print("Unregistered ISO at %s" % (colPath(ctx, loc)))
    23722372
    23732373    return 0
    23742374
    23752375def removeIsoCmd(ctx, args):
    2376     if (len(args) != 2):
    2377         print "usage: removeIso path"
     2376    if len(args) != 2:
     2377        print("usage: removeIso path")
    23782378        return 0
    23792379
     
    23832383        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    23842384    except:
    2385         print "no DVD with path %s registered" % (loc)
     2385        print("no DVD with path %s registered" % (loc))
    23862386        return 0
    23872387
    23882388    progress = dvd.deleteStorage()
    23892389    if progressBar(ctx, progress):
    2390         print "Removed ISO at %s" % (colPath(ctx, dvd.location))
     2390        print("Removed ISO at %s" % (colPath(ctx, dvd.location)))
    23912391    else:
    23922392        reportError(ctx, progress)
     
    23942394
    23952395def attachIsoCmd(ctx, args):
    2396     if (len(args) < 3):
    2397         print "usage: attachIso vm iso controller port:slot"
     2396    if len(args) < 3:
     2397        print("usage: attachIso vm iso controller port:slot")
    23982398        return 0
    23992399
     
    24062406        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    24072407    except:
    2408         print "no DVD with path %s registered" % (loc)
     2408        print("no DVD with path %s registered" % (loc))
    24092409        return 0
    24102410    if len(args) > 3:
     
    24172417
    24182418def detachIsoCmd(ctx, args):
    2419     if (len(args) < 3):
    2420         print "usage: detachIso vm iso"
     2419    if len(args) < 3:
     2420        print("usage: detachIso vm iso")
    24212421        return 0
    24222422
     
    24292429        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    24302430    except:
    2431         print "no DVD with path %s registered" % (loc)
     2431        print("no DVD with path %s registered" % (loc))
    24322432        return 0
    24332433
     
    24362436
    24372437def mountIsoCmd(ctx, args):
    2438     if (len(args) < 3):
    2439         print "usage: mountIso vm iso controller port:slot"
     2438    if len(args) < 3:
     2439        print("usage: mountIso vm iso controller port:slot")
    24402440        return 0
    24412441
     
    24482448        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False)
    24492449    except:
    2450         print "no DVD with path %s registered" % (loc)
     2450        print("no DVD with path %s registered" % (loc))
    24512451        return 0
    24522452
     
    24632463
    24642464def unmountIsoCmd(ctx, args):
    2465     if (len(args) < 2):
    2466         print "usage: unmountIso vm controller port:slot"
     2465    if len(args) < 2:
     2466        print("usage: unmountIso vm controller port:slot")
    24672467        return 0
    24682468
     
    24902490
    24912491def attachCtrCmd(ctx, args):
    2492     if (len(args) < 4):
    2493         print "usage: attachCtr vm cname bus <type>"
     2492    if len(args) < 4:
     2493        print("usage: attachCtr vm cname bus <type>")
    24942494        return 0
    24952495
     
    24972497        ctrltype = enumFromString(ctx, 'StorageControllerType', args[4])
    24982498        if ctrltype == None:
    2499             print "Controller type %s unknown" % (args[4])
     2499            print("Controller type %s unknown" % (args[4]))
    25002500            return 0
    25012501    else:
     
    25072507    bus = enumFromString(ctx, 'StorageBus', args[3])
    25082508    if bus is None:
    2509         print "Bus type %s unknown" % (args[3])
     2509        print("Bus type %s unknown" % (args[3]))
    25102510        return 0
    25112511    name = args[2]
     
    25142514
    25152515def detachCtrCmd(ctx, args):
    2516     if (len(args) < 3):
    2517         print "usage: detachCtr vm name"
     2516    if len(args) < 3:
     2517        print("usage: detachCtr vm name")
    25182518        return 0
    25192519
     
    25262526
    25272527def usbctr(ctx, mach, console, args):
    2528     if (args[0]):
     2528    if args[0]:
    25292529        console.attachUSBDevice(args[1], "")
    25302530    else:
     
    25322532
    25332533def attachUsbCmd(ctx, args):
    2534     if (len(args) < 3):
    2535         print "usage: attachUsb vm deviceuid"
     2534    if len(args) < 3:
     2535        print("usage: attachUsb vm deviceuid")
    25362536        return 0
    25372537
     
    25442544
    25452545def detachUsbCmd(ctx, args):
    2546     if (len(args) < 3):
    2547         print "usage: detachUsb vm deviceuid"
     2546    if len(args) < 3:
     2547        print("usage: detachUsb vm deviceuid")
    25482548        return 0
    25492549
     
    25572557
    25582558def guiCmd(ctx, args):
    2559     if (len(args) > 1):
    2560         print "usage: gui"
     2559    if len(args) > 1:
     2560        print("usage: gui")
    25612561        return 0
    25622562
     
    25722572
    25732573def shareFolderCmd(ctx, args):
    2574     if (len(args) < 4):
    2575         print "usage: shareFolder vm path name <writable> <persistent>"
     2574    if len(args) < 4:
     2575        print("usage: shareFolder vm path name <writable> <persistent>")
    25762576        return 0
    25772577
     
    25962596
    25972597def unshareFolderCmd(ctx, args):
    2598     if (len(args) < 3):
    2599         print "usage: unshareFolder vm name"
     2598    if len(args) < 3:
     2599        print("usage: unshareFolder vm name")
    26002600        return 0
    26012601
     
    26172617def snapshotCmd(ctx, args):
    26182618    if (len(args) < 2 or args[1] == 'help'):
    2619         print "Take snapshot:    snapshot vm take name <description>"
    2620         print "Restore snapshot: snapshot vm restore name"
    2621         print "Merge snapshot:   snapshot vm merge name"
     2619        print("Take snapshot:    snapshot vm take name <description>")
     2620        print("Restore snapshot: snapshot vm restore name")
     2621        print("Merge snapshot:   snapshot vm merge name")
    26222622        return 0
    26232623
     
    26272627    cmd = args[2]
    26282628    if cmd == 'take':
    2629         if (len(args) < 4):
    2630             print "usage: snapshot vm take name <description>"
     2629        if len(args) < 4:
     2630            print("usage: snapshot vm take name <description>")
    26312631            return 0
    26322632        name = args[3]
    2633         if (len(args) > 4):
     2633        if len(args) > 4:
    26342634            desc = args[4]
    26352635        else:
     
    26392639
    26402640    if cmd == 'restore':
    2641         if (len(args) < 4):
    2642             print "usage: snapshot vm restore name"
     2641        if len(args) < 4:
     2642            print("usage: snapshot vm restore name")
    26432643            return 0
    26442644        name = args[3]
     
    26482648
    26492649    if cmd == 'restorecurrent':
    2650         if (len(args) < 4):
    2651             print "usage: snapshot vm restorecurrent"
     2650        if len(args) < 4:
     2651            print("usage: snapshot vm restorecurrent")
    26522652            return 0
    26532653        snap = mach.currentSnapshot()
     
    26562656
    26572657    if cmd == 'delete':
    2658         if (len(args) < 4):
    2659             print "usage: snapshot vm delete name"
     2658        if len(args) < 4:
     2659            print("usage: snapshot vm delete name")
    26602660            return 0
    26612661        name = args[3]
     
    26642664        return 0
    26652665
    2666     print "Command '%s' is unknown" % (cmd)
     2666    print("Command '%s' is unknown" % (cmd))
    26672667    return 0
    26682668
     
    26832683        first = 0
    26842684        msg = ''
    2685         for aliasmode, aliaskey in alias.iteritems():
     2685        for aliasmode, aliaskey in list(alias.items()):
    26862686            if first == 0:
    26872687                first = 1
     
    26892689                msg += ', '
    26902690            if int(nat.aliasMode) & aliaskey:
    2691                 msg += '%d: %s' % (aliasmode, 'on')
     2691                msg += '%s: %s' % (aliasmode, 'on')
    26922692            else:
    2693                 msg += '%d: %s' % (aliasmode, 'off')
    2694         msg += ')'
     2693                msg += '%s: %s' % (aliasmode, 'off')
    26952694        return (0, [msg])
    26962695    else:
     
    26982697        if 'default' not in args:
    26992698            for a in range(1, len(args)):
    2700                 if not alias.has_key(args[a]):
    2701                     print 'Invalid alias mode: ' + args[a]
    2702                     print natAlias.__doc__
     2699                if args[a] not in alias:
     2700                    print('Invalid alias mode: ' + args[a])
     2701                    print(natAlias.__doc__)
    27032702                    return (1, None)
    27042703                nat.aliasMode = int(nat.aliasMode) | alias[args[a]]
     
    27232722    else:
    27242723        if args[1] < 16000:
    2725             print 'invalid mtu value (%s not in range [65 - 16000])' % (args[1])
     2724            print('invalid mtu value (%s not in range [65 - 16000])' % (args[1]))
    27262725            return (1, None)
    27272726        for i in range(2, len(args)):
    27282727            if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
    2729                 print 'invalid %s parameter (%i not in range [8-1024])' % (i, args[i])
     2728                print('invalid %s parameter (%i not in range [8-1024])' % (i, args[i]))
    27302729                return (1, None)
    27312730        a = [args[1]]
     
    27352734        else:
    27362735            for i in range(2, len(args)): a.append(args[i])
    2737         #print a
     2736        #print(a)
    27382737        nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
    27392738    return (0, None)
     
    27862785        cmd = args[1]
    27872786        if len(args) != 3:
    2788             print 'invalid args:', args
    2789             print natTftp.__doc__
     2787            print('invalid args:', args)
     2788            print(natTftp.__doc__)
    27902789            return (1, None)
    27912790        if cmd == 'prefix': nat.TFTPPrefix = args[2]
     
    27932792        elif cmd == 'server': nat.TFTPNextServer = args[2]
    27942793        else:
    2795             print "invalid cmd:", cmd
     2794            print("invalid cmd:", cmd)
    27962795            return (1, None)
    27972796    return (0, None)
     
    28182817        pfcmd = {
    28192818            'simple': {
    2820                 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
     2819                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 5,
    28212820                'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
    28222821            },
    28232822            'no_name': {
    2824                 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
     2823                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 7,
    28252824                'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
    28262825            },
    28272826            'ex': {
    2828                 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
     2827                'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 8,
    28292828                'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
    28302829            },
     
    28362835
    28372836        if not pfcmd[args[1]]['validate']():
    2838             print 'invalid port-forwarding or args of sub command ', args[1]
    2839             print natPortForwarding.__doc__
     2837            print('invalid port-forwarding or args of sub command ', args[1])
     2838            print(natPortForwarding.__doc__)
    28402839            return (1, None)
    28412840
     
    28562855        (addr, mask) = args[1].split('/')
    28572856        if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
    2858             print 'Invalid arguments'
     2857            print('Invalid arguments')
    28592858            return (1, None)
    28602859        nat.network = args[1]
     
    28802879    if len(args) < 2 or args[1] == 'help':
    28812880        if len(args) > 2:
    2882             print natcommands[args[2]].__doc__
     2881            print(natcommands[args[2]].__doc__)
    28832882        else:
    2884             print natCmd.__doc__
     2883            print(natCmd.__doc__)
    28852884        return 0
    28862885    if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
    2887         print natCmd.__doc__
     2886        print(natCmd.__doc__)
    28882887        return 0
    28892888    mach = ctx['argsToMach'](args)
    28902889    if mach == None:
    2891         print "please specify vm"
    2892         return 0
    2893     if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType)):
    2894         print 'please specify adapter num %d isn\'t in range [0-%d]' % (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType))
     2890        print("please specify vm")
     2891        return 0
     2892    if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType))):
     2893        print('please specify adapter num %d isn\'t in range [0-%d]' % (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(mach.chipsetType)))
    28952894        return 0
    28962895    nicnum = int(args[2])
     
    29192918        for r in report:
    29202919            msg ='%s nic%d %s: %s' % (mach.name, nicnum, func, r)
    2921             print msg
     2920            print(msg)
    29222921    return 0
    29232922
     
    29302929        yesno = {'off' : 0, 'on' : 1}
    29312930        if args[1] not in yesno:
    2932             print '%s isn\'t acceptable, please choose %s' % (args[1], yesno.keys())
     2931            print('%s isn\'t acceptable, please choose %s' % (args[1], list(yesno.keys())))
    29332932            return (1, None)
    29342933        adapter.__setattr__(attr, yesno[args[1]])
     
    29532952    else:
    29542953        if not args[1].isdigit():
    2955             print '%s isn\'t a number' % (args[1])
    2956             print (1, None)
     2954            print('%s isn\'t a number' % (args[1]))
     2955            return (1, None)
    29572956        adapter.lineSpeed = int(args[1])
    29582957    return (0, None)
     
    29762975    if len(args) == 1:
    29772976        nictypes = ctx['const'].all_values('NetworkAdapterType')
    2978         for key in nictypes.keys():
     2977        for key in list(nictypes.keys()):
    29792978            if str(adapter.adapterType) == str(nictypes[key]):
    29802979                return (0, str(key))
     
    29822981    else:
    29832982        nictypes = ctx['const'].all_values('NetworkAdapterType')
    2984         if args[1] not in nictypes.keys():
    2985             print '%s not in acceptable values (%s)' % (args[1], nictypes.keys())
     2983        if args[1] not in list(nictypes.keys()):
     2984            print('%s not in acceptable values (%s)' % (args[1], list(nictypes.keys())))
    29862985            return (1, None)
    29872986        adapter.adapterType = nictypes[args[1]]
     
    30023001            ctx['global'].constants.NetworkAttachmentType_Generic: ('Generic', ''),
    30033002        }
    3004         import types
    3005         if type(adapter.attachmentType) != types.IntType:
     3003        if type(adapter.attachmentType) != int:
    30063004            t = str(adapter.attachmentType)
    30073005        else:
     
    30373035                'f': lambda: ctx['global'].constants.NetworkAttachmentType_Generic}
    30383036        }
    3039         if args[1] not in nicAttachmentType.keys():
    3040             print '%s not in acceptable values (%s)' % (args[1], nicAttachmentType.keys())
     3037        if args[1] not in list(nicAttachmentType.keys()):
     3038            print('%s not in acceptable values (%s)' % (args[1], list(nicAttachmentType.keys())))
    30413039            return (1, None)
    30423040        if not nicAttachmentType[args[1]]['v']():
    3043             print nicAttachmentType.__doc__
     3041            print(nicAttachmentType.__doc__)
    30443042            return (1, None)
    30453043        nicAttachmentType[args[1]]['p']()
     
    30673065        if len(args) == 3 \
    30683066           and args[2] in niccomand:
    3069             print niccomand[args[2]].__doc__
     3067            print(niccomand[args[2]].__doc__)
    30703068        else:
    3071             print nicCmd.__doc__
     3069            print(nicCmd.__doc__)
    30723070        return 0
    30733071
    30743072    vm = ctx['argsToMach'](args)
    30753073    if vm is None:
    3076         print 'please specify vm'
     3074        print('please specify vm')
    30773075        return 0
    30783076
    30793077    if    len(args) < 3 \
    3080        or int(args[2]) not in range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)):
    3081         print 'please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))
     3078       or int(args[2]) not in list(range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))):
     3079        print('please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)))
    30823080        return 0
    30833081    nicnum = int(args[2])
     
    30923090        vm.saveSettings()
    30933091    if report is not None:
    3094         print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report)
     3092        print('%s nic %d %s: %s' % (vm.name, nicnum, args[3], report))
    30953093    session.unlockMachine()
    30963094    return 0
     
    30993097def promptCmd(ctx, args):
    31003098    if    len(args) < 2:
    3101         print "Current prompt: '%s'" % (ctx['prompt'])
     3099        print("Current prompt: '%s'" % (ctx['prompt']))
    31023100        return 0
    31033101
     
    31073105def foreachCmd(ctx, args):
    31083106    if len(args) < 3:
    3109         print "usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']"
     3107        print("usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']")
    31103108        return 0
    31113109
     
    31173115            e.apply(cmd)
    31183116    except:
    3119         print "Error executing"
     3117        print("Error executing")
    31203118        traceback.print_exc()
    31213119    return 0
     
    31233121def foreachvmCmd(ctx, args):
    31243122    if len(args) < 2:
    3125         print "foreachvm command <args>"
     3123        print("foreachvm command <args>")
    31263124        return 0
    31273125    cmdargs = args[1:]
     
    31333131
    31343132def recordDemoCmd(ctx, args):
    3135     if (len(args) < 3):
    3136         print "usage: recordDemo vm filename (duration)"
     3133    if len(args) < 3:
     3134        print("usage: recordDemo vm filename (duration)")
    31373135        return 0
    31383136    mach = argsToMach(ctx, args)
     
    31473145
    31483146def playbackDemoCmd(ctx, args):
    3149     if (len(args) < 3):
    3150         print "usage: playbackDemo vm filename (duration)"
     3147    if len(args) < 3:
     3148        print("usage: playbackDemo vm filename (duration)")
    31513149        return 0
    31523150    mach = argsToMach(ctx, args)
     
    31693167    for a in assigned:
    31703168        if a.isPhysicalDevice:
    3171             print "%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress))
     3169            print("%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)))
    31723170
    31733171    atts = ctx['global'].getArray(console, 'attachedPCIDevices')
    31743172    for a in atts:
    31753173        if a.isPhysicalDevice:
    3176             print "%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress))
     3174            print("%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)))
    31773175        else:
    3178             print "%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress))
     3176            print("%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress)))
    31793177    return
    31803178
     
    31883186
    31893187def lspciCmd(ctx, args):
    3190     if (len(args) < 2):
    3191         print "usage: lspci vm"
     3188    if len(args) < 2:
     3189        print("usage: lspci vm")
    31923190        return 0
    31933191    mach = argsToMach(ctx, args)
     
    31983196
    31993197def attachpciCmd(ctx, args):
    3200     if (len(args) < 3):
    3201         print "usage: attachpci vm hostpci <guestpci>"
     3198    if len(args) < 3:
     3199        print("usage: attachpci vm hostpci <guestpci>")
    32023200        return 0
    32033201    mach = argsToMach(ctx, args)
     
    32063204    hostaddr = parsePci(args[2])
    32073205    if hostaddr == -1:
    3208         print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])
    3209         return 0
    3210 
    3211     if (len(args) > 3):
     3206        print("invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]))
     3207        return 0
     3208
     3209    if len(args) > 3:
    32123210        guestaddr = parsePci(args[3])
    32133211        if guestaddr == -1:
    3214             print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3])
     3212            print("invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3]))
    32153213            return 0
    32163214    else:
     
    32203218
    32213219def detachpciCmd(ctx, args):
    3222     if (len(args) < 3):
    3223         print "usage: detachpci vm hostpci"
     3220    if len(args) < 3:
     3221        print("usage: detachpci vm hostpci")
    32243222        return 0
    32253223    mach = argsToMach(ctx, args)
     
    32283226    hostaddr = parsePci(args[2])
    32293227    if hostaddr == -1:
    3230         print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])
     3228        print("invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]))
    32313229        return 0
    32323230
     
    32353233
    32363234def gotoCmd(ctx, args):
    3237     if (len(args) < 2):
    3238         print "usage: goto line"
     3235    if len(args) < 2:
     3236        print("usage: goto line")
    32393237        return 0
    32403238
     
    32733271            'verbose':['Toggle verbosity', verboseCmd, 0],
    32743272            'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
    3275             'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name, "has", m.memorySize, "M"\'', evalCmd, 0],
     3273            'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print(m.name, "has", m.memorySize, "M")\'', evalCmd, 0],
    32763274            'quit':['Exits', quitCmd, 0],
    32773275            'host':['Show host information', hostCmd, 0],
     
    33293327            'prompt' : ['Control shell prompt', promptCmd, 0],
    33303328            'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0],
    3331             'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print obj.name"', foreachCmd, 0],
     3329            'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print(obj.name)"', foreachCmd, 0],
    33323330            'recordDemo':['Record demo: recordDemo Win32 file.dmo 10', recordDemoCmd, 0],
    33333331            'playbackDemo':['Playback demo: playbackDemo Win32 file.dmo 10', playbackDemoCmd, 0],
     
    33443342    ci = commands.get(c, None)
    33453343    if ci == None:
    3346         print "Unknown command: '%s', type 'help' for list of known commands" % (c)
     3344        print("Unknown command: '%s', type 'help' for list of known commands" % (c))
    33473345        return 0
    33483346    if ctx['remote'] and ctx['vb'] is None:
    33493347        if c not in ['connect', 'reconnect', 'help', 'quit']:
    3350             print "First connect to remote server with %s command." % (colored('connect', 'blue'))
     3348            print("First connect to remote server with %s command." % (colored('connect', 'blue')))
    33513349            return 0
    33523350    return ci[1](ctx, args)
     
    33543352
    33553353def runCommand(ctx, cmd):
    3356     if len(cmd) == 0: return 0
     3354    if not cmd: return 0
    33573355    args = split_no_quotes(cmd)
    33583356    if len(args) == 0: return 0
     
    33643362#
    33653363# def runTestCmd(ctx, args):
    3366 #    print "Testy test", ctx['vb']
     3364#    print("Testy test", ctx['vb'])
    33673365#    return 0
    33683366#
     
    33813379    d = {}
    33823380    try:
    3383         execfile(filename, d, d)
    3384         for (k, v) in d['commands'].items():
     3381        exec(compile(open(filename).read(), filename, 'exec'), d, d)
     3382        for (k, v) in list(d['commands'].items()):
    33853383            if g_fVerbose:
    3386                 print "customize: adding \"%s\" - %s" % (k, v[0])
     3384                print("customize: adding \"%s\" - %s" % (k, v[0]))
    33873385            cmds[k] = [v[0], v[1], filename]
    33883386    except:
    3389         print "Error loading user extensions from %s" % (filename)
     3387        print("Error loading user extensions from %s" % (filename))
    33903388        traceback.print_exc()
    33913389
     
    34233421    if vbox is not None:
    34243422        try:
    3425             print "Running VirtualBox version %s" % (vbox.version)
    3426         except Exception, e:
     3423            print("Running VirtualBox version %s" % (vbox.version))
     3424        except Exception as e:
    34273425            printErr(ctx, e)
    34283426            if g_fVerbose:
     
    34613459                cmd = 'runScript %s'% (g_sScriptFile)
    34623460            elif g_sCmd is not None:
    3463                 cmd = it.next()
     3461                cmd = next(it)
    34643462            else:
    3465                 cmd = raw_input(ctx['prompt'])
     3463                if sys.version_info[0] <= 2:
     3464                    cmd = raw_input(ctx['prompt'])
     3465                else:
     3466                    cmd = input(ctx['prompt'])
    34663467            done = runCommand(ctx, cmd)
    34673468            if done != 0: break
     
    34693470                break
    34703471        except KeyboardInterrupt:
    3471             print '====== You can type quit or q to leave'
     3472            print('====== You can type quit or q to leave')
    34723473        except StopIteration:
    34733474            break
    34743475        except EOFError:
    34753476            break
    3476         except Exception, e:
     3477        except Exception as e:
    34773478            printErr(ctx, e)
    34783479            if g_fVerbose:
     
    35363537
    35373538    if options.autopath:
    3538         asLocations = [ os.getcwd(), ];
    3539         try:    sScriptDir = os.path.dirname(os.path.abspath(__file__));
     3539        asLocations = [ os.getcwd(), ]
     3540        try:    sScriptDir = os.path.dirname(os.path.abspath(__file__))
    35403541        except: pass; # In case __file__ isn't there.
    35413542        else:
    35423543            if platform.system() in [ 'SunOS', ]:
    3543                 asLocations.append(os.path.join(sScriptDir, 'amd64'));
    3544             asLocations.append(sScriptDir);
     3544                asLocations.append(os.path.join(sScriptDir, 'amd64'))
     3545            asLocations.append(sScriptDir)
    35453546
    35463547
     
    35503551                if   os.path.isfile(os.path.join(sCurLoc, "VirtualBox")) \
    35513552                  or os.path.isfile(os.path.join(sCurLoc, "VirtualBox.exe")):
    3552                     print "Autodetected VBOX_PROGRAM_PATH as", sCurLoc
     3553                    print("Autodetected VBOX_PROGRAM_PATH as", sCurLoc)
    35533554                    os.environ["VBOX_PROGRAM_PATH"] = sCurLoc
    35543555                    sPath = sCurLoc
    3555                     break;
     3556                    break
    35563557        if sPath:
    35573558            sys.path.append(os.path.join(sPath, "sdk", "installer"))
     
    35613562            for sCurLoc in asLocations:
    35623563                if os.path.isfile(os.path.join(sCurLoc, "sdk", "bindings", "VirtualBox.xidl")):
    3563                     sCurLoc = os.path.join(sCurLoc, "sdk");
    3564                     print "Autodetected VBOX_SDK_PATH as", sCurLoc
     3564                    sCurLoc = os.path.join(sCurLoc, "sdk")
     3565                    print("Autodetected VBOX_SDK_PATH as", sCurLoc)
    35653566                    os.environ["VBOX_SDK_PATH"] = sCurLoc
    3566                     sPath = sCurLoc;
    3567                     break;
     3567                    sPath = sCurLoc
     3568                    break
    35683569        if sPath:
    3569             sTmp = os.path.join(sCurLoc, 'sdk', 'bindings', 'xpcom', 'python');
     3570            sTmp = os.path.join(sCurLoc, 'bindings', 'xpcom', 'python')
    35703571            if os.path.isdir(sTmp):
    3571                 sys.path.append(sTmp);
    3572             del sTmp;
    3573         del sPath, asLocations;
     3572                sys.path.append(sTmp)
     3573            del sTmp
     3574        del sPath, asLocations
    35743575
    35753576
  • trunk/src/VBox/Installer/common/vboxapisetup.py

    r59795 r59798  
    11"""
    2 Copyright (C) 2009-2015 Oracle Corporation
     2Copyright (C) 2009-2016 Oracle Corporation
    33
    44This file is part of VirtualBox Open Source Edition (OSE), as
     
    1919    comCache1 = os.path.join(get_python_lib(), 'win32com', 'gen_py')
    2020    comCache2 = os.path.join(os.environ.get("TEMP", "c:\\tmp"), 'gen_py')
    21     print "Cleaning COM cache at",comCache1,"and",comCache2
     21    print("Cleaning COM cache at",comCache1,"and",comCache2)
    2222    shutil.rmtree(comCache1, True)
    2323    shutil.rmtree(comCache2, True)
  • trunk/src/VBox/Main/glue/vboxapi.py

    r59795 r59798  
    77__copyright__ = \
    88    """
    9     Copyright (C) 2009-2015 Oracle Corporation
     9    Copyright (C) 2009-2016 Oracle Corporation
    1010
    1111    This file is part of VirtualBox Open Source Edition (OSE), as
     
    3232    xrange = range
    3333    long = int
    34     import builtins
    35     print_ = getattr(builtins, 'print', None)
    36 elif sys.version_info >= (2, 6):
    37     import __builtin__
    38     print_ = getattr(__builtin__, 'print', None)
    39 else:
    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)
    9234
    9335#
     
    225167    # Try case-insensitivity workaround for class attributes (COM methods).
    226168    sAttrLower = sAttr.lower()
    227     for k in self.__class__.__dict__.keys():
     169    for k in list(self.__class__.__dict__.keys()):
    228170        if k.lower() == sAttrLower:
    229171            setattr(self.__class__, sAttr, self.__class__.__dict__[k])
  • trunk/src/VBox/Main/webservice/websrv-python.xsl

    r59795 r59798  
    193193      if self.isarray:
    194194          return self.handle.__next()
    195       raise TypeError, "iteration over non-sequence"
     195      raise TypeError("iteration over non-sequence")
    196196
    197197   def __size(self):
    198198      if self.isarray:
    199199          return self.handle.__size()
    200       raise TypeError, "iteration over non-sequence"
     200      raise TypeError("iteration over non-sequence")
    201201
    202202   def __len__(self):
    203203      if self.isarray:
    204204          return self.handle.__len__()
    205       raise TypeError, "iteration over non-sequence"
     205      raise TypeError("iteration over non-sequence")
    206206
    207207   def __getitem__(self, index):
    208208      if self.isarray:
    209209          return <xsl:value-of select="$ifname" />(self.mgr, self.handle[index])
    210       raise TypeError, "iteration over non-sequence"
     210      raise TypeError("iteration over non-sequence")
    211211
    212212   def __str__(self):
     
    326326
    327327    def <xsl:call-template name="makeSetterName"><xsl:with-param name="attrname" select="@name"/></xsl:call-template>(self):
    328        raise Error, 'setters not supported'
     328       raise Error('setters not supported')
    329329    </xsl:for-each>
    330330
     
    332332      if self.isarray:
    333333          return self.handle.__next()
    334       raise TypeError, "iteration over non-sequence"
     334      raise TypeError("iteration over non-sequence")
    335335
    336336    def __size(self):
    337337      if self.isarray:
    338338          return self.handle.__size()
    339       raise TypeError, "iteration over non-sequence"
     339      raise TypeError("iteration over non-sequence")
    340340
    341341    def __len__(self):
    342342      if self.isarray:
    343343          return self.handle.__len__()
    344       raise TypeError, "iteration over non-sequence"
     344      raise TypeError("iteration over non-sequence")
    345345
    346346    def __getitem__(self, index):
    347347      if self.isarray:
    348348          return <xsl:value-of select="$ifname" />(self.mgr, self.handle[index])
    349       raise TypeError, "iteration over non-sequence"
     349      raise TypeError("iteration over non-sequence")
    350350<xsl:call-template name="xsltprocNewlineOutputHack"/>
    351351</xsl:template>
     
    511511     c = self.map.get(handle,-1)
    512512     if c == -1:
    513         raise Error, 'wrong refcount'
     513        raise Error('wrong refcount')
    514514     c = c - 1
    515515     if c == 0:
     
    533533      if self.isarray:
    534534          return self.handle.__next()
    535       raise TypeError, "iteration over non-sequence"
     535      raise TypeError("iteration over non-sequence")
    536536
    537537  def __size(self):
    538538      if self.isarray:
    539539          return self.handle.__size()
    540       raise TypeError, "iteration over non-sequence"
     540      raise TypeError("iteration over non-sequence")
    541541
    542542  def __len__(self):
    543543      if self.isarray:
    544544          return self.handle.__len__()
    545       raise TypeError, "iteration over non-sequence"
     545      raise TypeError("iteration over non-sequence")
    546546
    547547  def __getitem__(self, index):
    548548      if self.isarray:
    549549          return String(self.mgr, self.handle[index])
    550       raise TypeError, "iteration over non-sequence"
     550      raise TypeError("iteration over non-sequence")
    551551
    552552  def __str__(self):
     
    624624      if self.isarray:
    625625          return self.handle.__next()
    626       raise TypeError, "iteration over non-sequence"
     626      raise TypeError("iteration over non-sequence")
    627627
    628628  def __size(self):
    629629      if self.isarray:
    630630          return self.handle.__size()
    631       raise TypeError, "iteration over non-sequence"
     631      raise TypeError("iteration over non-sequence")
    632632
    633633  def __len__(self):
    634634      if self.isarray:
    635635          return self.handle.__len__()
    636       raise TypeError, "iteration over non-sequence"
     636      raise TypeError("iteration over non-sequence")
    637637
    638638  def __getitem__(self, index):
    639639      if self.isarray:
    640640          return Boolean(self.mgr, self.handle[index])
    641       raise TypeError, "iteration over non-sequence"
     641      raise TypeError("iteration over non-sequence")
    642642
    643643class Number:
     
    650650      if self.isarray:
    651651          return self.handle.__next()
    652       raise TypeError, "iteration over non-sequence"
     652      raise TypeError("iteration over non-sequence")
    653653
    654654  def __size(self):
    655655      if self.isarray:
    656656          return self.handle.__size()
    657       raise TypeError, "iteration over non-sequence"
     657      raise TypeError("iteration over non-sequence")
    658658
    659659  def __len__(self):
    660660      if self.isarray:
    661661          return self.handle.__len__()
    662       raise TypeError, "iteration over non-sequence"
     662      raise TypeError("iteration over non-sequence")
    663663
    664664  def __str__(self):
     
    711711           self.handle = mgr.decodebase64(handle)
    712712       else:
    713            raise TypeError, "only octet arrays"
     713           raise TypeError("only octet arrays")
    714714
    715715  def __getitem__(self, index):
     
    731731      if self.isarray:
    732732          return UnsignedInt(self.mgr, self.handle[index])
    733       raise TypeError, "iteration over non-sequence"
     733      raise TypeError("iteration over non-sequence")
    734734
    735735
     
    743743      if self.isarray:
    744744          return Int(self.mgr, self.handle[index])
    745       raise TypeError, "iteration over non-sequence"
     745      raise TypeError("iteration over non-sequence")
    746746
    747747class UnsignedShort(Number):
     
    754754      if self.isarray:
    755755          return UnsignedShort(self.mgr, self.handle[index])
    756       raise TypeError, "iteration over non-sequence"
     756      raise TypeError("iteration over non-sequence")
    757757
    758758class Short(Number):
     
    765765      if self.isarray:
    766766          return Short(self.mgr, self.handle[index])
    767       raise TypeError, "iteration over non-sequence"
     767      raise TypeError("iteration over non-sequence")
    768768
    769769class UnsignedLong(Number):
     
    776776      if self.isarray:
    777777          return UnsignedLong(self.mgr, self.handle[index])
    778       raise TypeError, "iteration over non-sequence"
     778      raise TypeError("iteration over non-sequence")
    779779
    780780class Long(Number):
     
    787787      if self.isarray:
    788788          return Long(self.mgr, self.handle[index])
    789       raise TypeError, "iteration over non-sequence"
     789      raise TypeError("iteration over non-sequence")
    790790
    791791class Double(Number):
     
    798798      if self.isarray:
    799799          return Double(self.mgr, self.handle[index])
    800       raise TypeError, "iteration over non-sequence"
     800      raise TypeError("iteration over non-sequence")
    801801
    802802class Float(Number):
     
    809809      if self.isarray:
    810810          return Float(self.mgr, self.handle[index])
    811       raise TypeError, "iteration over non-sequence"
     811      raise TypeError("iteration over non-sequence")
    812812
    813813class IUnknown:
     
    826826      if self.isarray:
    827827          return self.handle.__next()
    828       raise TypeError, "iteration over non-sequence"
     828      raise TypeError("iteration over non-sequence")
    829829
    830830  def __size(self):
    831831      if self.isarray:
    832832          return self.handle.__size()
    833       raise TypeError, "iteration over non-sequence"
     833      raise TypeError("iteration over non-sequence")
    834834
    835835  def __len__(self):
    836836      if self.isarray:
    837837          return self.handle.__len__()
    838       raise TypeError, "iteration over non-sequence"
     838      raise TypeError("iteration over non-sequence")
    839839
    840840  def __getitem__(self, index):
    841841      if self.isarray:
    842842          return IUnknown(self.mgr, self.handle[index])
    843       raise TypeError, "iteration over non-sequence"
     843      raise TypeError("iteration over non-sequence")
    844844
    845845  def __str__(self):
  • trunk/src/VBox/ValidationKit/testdriver/vbox.py

    r59795 r59798  
    99__copyright__ = \
    1010"""
    11 Copyright (C) 2010-2015 Oracle Corporation
     11Copyright (C) 2010-2016 Oracle Corporation
    1212
    1313This file is part of VirtualBox Open Source Edition (OSE), as
  • trunk/src/libs/xpcom18a4/python/Makefile.kmk

    r59795 r59798  
    55
    66#
    7 # Copyright (C) 2009-2015 Oracle Corporation
     7# Copyright (C) 2009-2016 Oracle Corporation
    88#
    99# This file is part of VirtualBox Open Source Edition (OSE), as
     
    2727#
    2828# List of supported Python versions, defining a number of
    29 # VBOX_PYTHON[25|26|27|DEF]_[INC|LIB] variables which get picked up below.
     29# VBOX_PYTHON[26|27|31|32|33|34|35|DEF]_[INC|LIB] variables
     30# which get picked up below.
    3031#
    3132ifeq ($(KBUILD_TARGET),darwin) # Relatively predictable, don't script.
    32  ifeq ($(KBUILD_TARGET_ARCH),x86)
    33   VBOX_PYTHON25_INC = $(VBOX_PATH_MACOSX_SDK)/usr/include/python2.5
    34   VBOX_PYTHON25_LIB = $(VBOX_PATH_MACOSX_SDK)/usr/lib/libpython2.5.dylib
    35   VBOX_PYTHON25_LIB_X86 = $(VBOX_PYTHON25_LIB)
    36  endif
    3733 if  !defined(VBOX_WITHOUT_VBOXPYTHON_FOR_OSX_10_6) \
    3834  && (   !defined(VBOX_OSE) \
     
    4945  VBOX_PYTHON27_LIB_X86 = $(VBOX_PYTHON27_LIB)
    5046 endif
     47 # No Python 3.x yet as part of OSX versions including El Capitan, 10.11.
    5148
    5249else
     
    115112
    116113
    117 ifdef VBOX_PYTHON23_INC
    118 #
    119 # Python 2.3 version
    120 #
    121 DLLS += VBoxPython2_3
    122 VBoxPython2_3_EXTENDS    = VBoxPythonBase
    123 VBoxPython2_3_EXTENDS_BY = appending
    124 VBoxPython2_3_TEMPLATE   = XPCOM$(if-expr "$(KBUILD_TARGET)" == "darwin",OSX104,)
    125 VBoxPython2_3_INCS       = $(VBOX_PYTHON23_INC)
    126 VBoxPython2_3_LIBS       = $(VBOX_PYTHON23_LIB)
    127 
    128  ifdef VBOX_WITH_32_ON_64_MAIN_API
    129 DLLS += VBoxPython2_3_x86
    130 VBoxPython2_3_x86_EXTENDS    = VBoxPythonBase_x86
    131 VBoxPython2_3_x86_EXTENDS_BY = appending
    132 VBoxPython2_3_x86_TEMPLATE   = XPCOM$(if-expr "$(KBUILD_TARGET)" == "darwin",OSX104,-x86)
    133 VBoxPython2_3_x86_INCS       = $(VBOX_PYTHON23_INC)
    134 VBoxPython2_3_x86_LIBS       = $(VBOX_PYTHON23_LIB_X86)
    135  endif
    136 endif
    137 
    138 ifdef VBOX_PYTHON24_INC
    139 #
    140 # Python 2.4 version
    141 #
    142 DLLS += VBoxPython2_4
    143 VBoxPython2_4_EXTENDS    = VBoxPythonBase
    144 VBoxPython2_4_EXTENDS_BY = appending
    145 VBoxPython2_4_INCS       = $(VBOX_PYTHON24_INC)
    146 VBoxPython2_4_LIBS       = $(VBOX_PYTHON24_LIB)
    147 
    148  ifdef VBOX_WITH_32_ON_64_MAIN_API
    149 DLLS += VBoxPython2_4_x86
    150 VBoxPython2_4_x86_EXTENDS    = VBoxPythonBase_x86
    151 VBoxPython2_4_x86_EXTENDS_BY = appending
    152 VBoxPython2_4_x86_INCS       = $(VBOX_PYTHON24_INC)
    153 VBoxPython2_4_x86_LIBS       = $(VBOX_PYTHON24_LIB_X86)
    154  endif
    155 endif
    156 
    157 ifdef VBOX_PYTHON25_INC
    158 #
    159 # Python 2.5 version
    160 #
    161 DLLS += VBoxPython2_5
    162 VBoxPython2_5_EXTENDS    = VBoxPythonBase
    163 VBoxPython2_5_EXTENDS_BY = appending
    164 VBoxPython2_5_INCS       = $(VBOX_PYTHON25_INC)
    165 VBoxPython2_5_LIBS       = $(VBOX_PYTHON25_LIB)
    166 
    167  ifdef VBOX_WITH_32_ON_64_MAIN_API
    168 DLLS += VBoxPython2_5_x86
    169 VBoxPython2_5_x86_EXTENDS    = VBoxPythonBase_x86
    170 VBoxPython2_5_x86_EXTENDS_BY = appending
    171 VBoxPython2_5_x86_INCS       = $(VBOX_PYTHON25_INC)
    172 VBoxPython2_5_x86_LIBS       = $(VBOX_PYTHON25_LIB_X86)
    173  endif
    174 endif
    175 
    176114ifdef VBOX_PYTHON26_INC
    177115#
     
    213151VBoxPython2_7_x86_INCS       = $(VBOX_PYTHON27_INC)
    214152VBoxPython2_7_x86_LIBS       = $(VBOX_PYTHON27_LIB_X86)
     153 endif
     154endif
     155
     156ifdef VBOX_PYTHON31_INC
     157#
     158# Python 3.1 version
     159#
     160DLLS += VBoxPython3_1
     161VBoxPython3_1_EXTENDS    = VBoxPythonBase
     162VBoxPython3_1_EXTENDS_BY = appending
     163VBoxPython3_1_TEMPLATE   = XPCOM
     164VBoxPython3_1_INCS       = $(VBOX_PYTHON31_INC)
     165VBoxPython3_1_LIBS       = $(VBOX_PYTHON31_LIB)
     166
     167 ifdef VBOX_WITH_32_ON_64_MAIN_API
     168DLLS += VBoxPython3_1_x86
     169VBoxPython3_1_x86_EXTENDS    = VBoxPythonBase_x86
     170VBoxPython3_1_x86_EXTENDS_BY = appending
     171VBoxPython3_1_x86_TEMPLATE   = XPCOM
     172VBoxPython3_1_x86_INCS       = $(VBOX_PYTHON31_INC)
     173VBoxPython3_1_x86_LIBS       = $(VBOX_PYTHON31_LIB_X86)
     174 endif
     175endif
     176
     177ifdef VBOX_PYTHON32_INC
     178#
     179# Python 3.2 version
     180#
     181DLLS += VBoxPython3_2
     182VBoxPython3_2_EXTENDS    = VBoxPythonBase
     183VBoxPython3_2_EXTENDS_BY = appending
     184VBoxPython3_2_TEMPLATE   = XPCOM
     185VBoxPython3_2_INCS       = $(VBOX_PYTHON32_INC)
     186VBoxPython3_2_LIBS       = $(VBOX_PYTHON32_LIB)
     187
     188 ifdef VBOX_WITH_32_ON_64_MAIN_API
     189DLLS += VBoxPython3_2_x86
     190VBoxPython3_2_x86_EXTENDS    = VBoxPythonBase_x86
     191VBoxPython3_2_x86_EXTENDS_BY = appending
     192VBoxPython3_2_x86_TEMPLATE   = XPCOM
     193VBoxPython3_2_x86_INCS       = $(VBOX_PYTHON32_INC)
     194VBoxPython3_2_x86_LIBS       = $(VBOX_PYTHON32_LIB_X86)
     195 endif
     196endif
     197
     198ifdef VBOX_PYTHON33_INC
     199#
     200# Python 3.3 version
     201#
     202DLLS += VBoxPython3_3
     203VBoxPython3_3_EXTENDS    = VBoxPythonBase
     204VBoxPython3_3_EXTENDS_BY = appending
     205VBoxPython3_3_TEMPLATE   = XPCOM
     206VBoxPython3_3_INCS       = $(VBOX_PYTHON33_INC)
     207VBoxPython3_3_LIBS       = $(VBOX_PYTHON33_LIB)
     208
     209 ifdef VBOX_WITH_32_ON_64_MAIN_API
     210DLLS += VBoxPython3_3_x86
     211VBoxPython3_3_x86_EXTENDS    = VBoxPythonBase_x86
     212VBoxPython3_3_x86_EXTENDS_BY = appending
     213VBoxPython3_3_x86_TEMPLATE   = XPCOM
     214VBoxPython3_3_x86_INCS       = $(VBOX_PYTHON33_INC)
     215VBoxPython3_3_x86_LIBS       = $(VBOX_PYTHON33_LIB_X86)
     216 endif
     217endif
     218
     219ifdef VBOX_PYTHON34_INC
     220#
     221# Python 3.4 version
     222#
     223DLLS += VBoxPython3_4
     224VBoxPython3_4_EXTENDS    = VBoxPythonBase
     225VBoxPython3_4_EXTENDS_BY = appending
     226VBoxPython3_4_TEMPLATE   = XPCOM
     227VBoxPython3_4_INCS       = $(VBOX_PYTHON34_INC)
     228VBoxPython3_4_LIBS       = $(VBOX_PYTHON34_LIB)
     229
     230 ifdef VBOX_WITH_32_ON_64_MAIN_API
     231DLLS += VBoxPython3_4_x86
     232VBoxPython3_4_x86_EXTENDS    = VBoxPythonBase_x86
     233VBoxPython3_4_x86_EXTENDS_BY = appending
     234VBoxPython3_4_x86_TEMPLATE   = XPCOM
     235VBoxPython3_4_x86_INCS       = $(VBOX_PYTHON34_INC)
     236VBoxPython3_4_x86_LIBS       = $(VBOX_PYTHON34_LIB_X86)
     237 endif
     238endif
     239
     240ifdef VBOX_PYTHON35_INC
     241#
     242# Python 3.5 version
     243#
     244DLLS += VBoxPython3_5
     245VBoxPython3_5_EXTENDS    = VBoxPythonBase
     246VBoxPython3_5_EXTENDS_BY = appending
     247VBoxPython3_5_TEMPLATE   = XPCOM
     248VBoxPython3_5_INCS       = $(VBOX_PYTHON35_INC)
     249VBoxPython3_5_LIBS       = $(VBOX_PYTHON35_LIB)
     250
     251 ifdef VBOX_WITH_32_ON_64_MAIN_API
     252DLLS += VBoxPython3_5_x86
     253VBoxPython3_5_x86_EXTENDS    = VBoxPythonBase_x86
     254VBoxPython3_5_x86_EXTENDS_BY = appending
     255VBoxPython3_5_x86_TEMPLATE   = XPCOM
     256VBoxPython3_5_x86_INCS       = $(VBOX_PYTHON35_INC)
     257VBoxPython3_5_x86_LIBS       = $(VBOX_PYTHON35_LIB_X86)
    215258 endif
    216259endif
  • trunk/src/libs/xpcom18a4/python/__init__.py

    r59795 r59798  
    3838
    3939# The XPCOM (Cross Platform COM) package.
    40 import exceptions
     40from __future__ import print_function
     41import sys
     42if sys.version_info[0] <= 2:
     43    import exceptions
     44    XPCOMBaseException = exceptions.Exception
     45else:
     46    XPCOMBaseException = Exception
    4147
    4248# A global "verbose" flag - currently used by the
     
    4854# The standard XPCOM exception object.
    4955# Instances of this class are raised by the XPCOM extension module.
    50 class Exception(exceptions.Exception):
     56class Exception(XPCOMBaseException):
    5157    def __init__(self, errno, message = None):
    5258        assert int(errno) == errno, "The errno param must be an integer"
    5359        self.errno = errno
    5460        self.msg = message
    55         exceptions.Exception.__init__(self, errno)
     61        XPCOMBaseException.__init__(self, errno)
    5662    def __str__(self):
    5763        if not hr_map:
    58             import nsError
    59             for name, val in nsError.__dict__.items():
     64            from . import nsError
     65            for name, val in list(nsError.__dict__.items()):
    6066                if type(val)==type(0):
    6167                    hr_map[val] = name
     
    8086    def __init__(self, errno=None, *args, **kw):
    8187        if errno is None:
    82             import nsError
     88            from . import nsError
    8389            errno = nsError.NS_ERROR_FAILURE
    8490        Exception.__init__(self, errno, *args, **kw)
     
    98104        pass
    99105    def write(self, msg):
    100         import _xpcom
     106        import xpcom._xpcom as _xpcom
    101107        _xpcom.LogConsoleMessage(msg)
    102108    def close(self):
     
    104110
    105111def setupLogging():
    106     import sys, os, threading, thread
     112    import os
     113    if sys.version_info[0] <= 2:
     114        import threading, thread
    107115    hdlr = logging.StreamHandler(ConsoleServiceStream())
    108116    fmt = logging.Formatter(logging.BASIC_FORMAT)
     
    113121    # Later versions of logging use an RLock, so we detect an "old" style
    114122    # handler and update its lock
    115     if type(hdlr.lock) == thread.LockType:
    116         hdlr.lock = threading.RLock()
     123    if sys.version_info[0] <= 2:
     124        if type(hdlr.lock) == thread.LockType:
     125            hdlr.lock = threading.RLock()
    117126
    118127    logger.addHandler(hdlr)
     
    126135            # open without buffering so never pending output
    127136            stream = open(filename, "wU", 0)
    128         except IOError, why:
    129             print >> sys.stderr, "pyxpcom failed to open log file '%s': %s" \
    130                                  % (filename, why)
     137        except IOError as why:
     138            print("pyxpcom failed to open log file '%s': %s"  % (filename, why), file=sys.stderr)
    131139            # stream remains default
    132140
    133141    hdlr = logging.StreamHandler(stream)
    134142    # see above - fix a deadlock problem on this handler too.
    135     if type(hdlr.lock) == thread.LockType:
    136         hdlr.lock = threading.RLock()
     143    if sys.version_info[0] <= 2:
     144        if type(hdlr.lock) == thread.LockType:
     145            hdlr.lock = threading.RLock()
    137146
    138147    fmt = logging.Formatter(logging.BASIC_FORMAT)
  • trunk/src/libs/xpcom18a4/python/client/__init__.py

    r59795 r59798  
    3737
    3838import os
    39 import new
     39from types import MethodType
    4040import logging
    4141from xpcom import xpt, COMException, nsError, logger
     
    126126    # Exec the code object
    127127    tempNameSpace = {}
    128     exec codeObject in globals(), tempNameSpace
     128    exec(codeObject, globals(), tempNameSpace)
    129129    ret = tempNameSpace[name]
    130     if not interface_method_cache.has_key(iid):
     130    if iid not in interface_method_cache:
    131131        interface_method_cache[iid] = {}
    132132    interface_method_cache[iid][name] = ret
     
    153153            if flags & FLAGS_TO_IGNORE == 0:
    154154                if flags & XPT_MD_SETTER:
    155                     param_flags = map(lambda x: (x.param_flags,) + xpt.MakeReprForInvoke(x), m.params)
     155                    param_flags = list([(x.param_flags,) + xpt.MakeReprForInvoke(x) for x in m.params])
    156156                    setters[m.name] = m.method_index, param_flags
    157157                elif flags & XPT_MD_GETTER:
    158                     param_flags = map(lambda x: (x.param_flags,) + xpt.MakeReprForInvoke(x), m.params)
     158                    param_flags = list([(x.param_flags,) + xpt.MakeReprForInvoke(x) for x in m.params])
    159159                    getters[m.name] = m.method_index, param_flags
    160160                else:
     
    220220            except COMException:
    221221                pass
    222         raise ValueError, "This object does not support automatic numeric conversion to this type"
     222        raise ValueError("This object does not support automatic numeric conversion to this type")
    223223
    224224    def __int__(self):
     
    281281                for nominated_iid in interface_infos:
    282282                    # Interface may appear twice in the class info list, so check this here.
    283                     if not self.__dict__['_interface_infos_'].has_key(nominated_iid):
     283                    if nominated_iid not in self.__dict__['_interface_infos_']:
    284284                        # Just invoke our QI on the object
    285285                        self.queryInterface(nominated_iid)
     
    290290                    contractid_info_cache[real_cid] = contractid_info
    291291            else:
    292                 for key, val in contractid_info.items():
     292                for key, val in list(contractid_info.items()):
    293293                    self.__dict__[key].update(val)
    294294
     
    300300        # rebuild the world for each new object.
    301301        iis = self.__dict__['_interface_infos_']
    302         assert not iis.has_key(iid), "Already remembered this interface!"
     302        assert iid not in iis, "Already remembered this interface!"
    303303        try:
    304304            method_infos, getters, setters, constants = BuildInterfaceInfo(iid)
    305         except COMException, why:
     305        except COMException as why:
    306306            # Failing to build an interface info generally isn't a real
    307307            # problem - its probably just that the interface is non-scriptable.
     
    314314        iis[iid] = method_infos, getters, setters, constants
    315315        names = self.__dict__['_name_to_interface_iid_']
    316         for name in method_infos.keys(): names[name] = iid
    317         for name in getters.keys(): names[name] = iid
    318         for name in setters.keys(): names[name] = iid
    319         for name in constants.keys():  names[name] = iid
     316        for name in list(method_infos.keys()): names[name] = iid
     317        for name in list(getters.keys()): names[name] = iid
     318        for name in list(setters.keys()): names[name] = iid
     319        for name in list(constants.keys()):  names[name] = iid
    320320
    321321    def QueryInterface(self, iid):
    322         if self._interfaces_.has_key(iid):
    323             assert self._interface_names_.has_key(iid.name), "_interfaces_ has the key, but _interface_names_ does not!"
     322        if iid in self._interfaces_:
     323            assert iid_name in self._interface_names_, "_interfaces_ has the key, but _interface_names_ does not!"
    324324            return self
    325325        # Haven't seen this before - do a real QI.
    326         if not self._interface_infos_.has_key(iid):
     326        if iid not in self._interface_infos_:
    327327            self._remember_interface_info(iid)
    328328        iface_info = self._interface_infos_[iid]
     
    350350    def __getattr__(self, attr):
    351351        if attr in _special_getattr_names:
    352             raise AttributeError, attr
     352            raise AttributeError(attr)
    353353        # First allow the interface name to return the "raw" interface
    354354        interface = self.__dict__['_interface_names_'].get(attr, None)
     
    375375        # Some interfaces may provide this name via "native" support.
    376376        # Loop over all interfaces, and if found, cache it for next time.
    377         for interface in self.__dict__['_interfaces_'].values():
     377        for interface in list(self.__dict__['_interfaces_'].values()):
    378378            try:
    379379                ret = getattr(interface, attr)
     
    382382            except AttributeError:
    383383                pass
    384         raise AttributeError, "XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr)
     384        raise AttributeError("XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr))
    385385       
    386386    def __setattr__(self, attr, val):
     
    397397            setattr(interface, attr, val)
    398398            return
    399         raise AttributeError, "XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr)
     399        raise AttributeError("XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr))
    400400
    401401    def _get_classinfo_repr_(self):
     
    410410            self.__dict__['_tried_classinfo_'] = 0
    411411
    412         iface_names = self.__dict__['_interface_names_'].keys()
     412        iface_names = list(self.__dict__['_interface_names_'].keys())
    413413        try:
    414414            iface_names.remove("nsISupports")
     
    436436        self.__dict__.update(constants)
    437437        # We remember the constant names to prevent the user trying to assign to them!
    438         self.__dict__['_constant_names_'] = constants.keys()
     438        self.__dict__['_constant_names_'] = list(constants.keys())
    439439
    440440    def __getattr__(self, attr):
    441441        # Allow the underlying interface to provide a better implementation if desired.
    442442        if attr in _special_getattr_names:
    443             raise AttributeError, attr
     443            raise AttributeError(attr)
    444444
    445445        ret = getattr(self.__dict__['_comobj_'], attr, None)
     
    449449        unbound_method = self.__dict__['_methods_'].get(attr, None)
    450450        if unbound_method is not None:
    451             return new.instancemethod(unbound_method, self, self.__class__)
     451            return MethodType(unbound_method, self)
    452452
    453453        getters = self.__dict__['_property_getters_']
     
    456456            method_index, param_infos = info
    457457            if len(param_infos)!=1: # Only expecting a retval
    458                 raise RuntimeError, "Can't get properties with this many args!"
     458                raise RuntimeError("Can't get properties with this many args!")
    459459            args = ( param_infos, () )
    460460            return XPTC_InvokeByIndex(self._comobj_, method_index, args)
     
    467467            # Cache it locally
    468468            self.__dict__['_methods_'][attr] = unbound_method
    469             return new.instancemethod(unbound_method, self, self.__class__)
    470 
    471         raise AttributeError, "XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr)
     469            return MethodType(unbound_method, self)
     470
     471        raise AttributeError("XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr))
    472472
    473473    def __setattr__(self, attr, val):
    474474        # If we already have a __dict__ item of that name, and its not one of
    475475        # our constants, we just directly set it, and leave.
    476         if self.__dict__.has_key(attr) and attr not in self.__dict__['_constant_names_']:
     476        if attr in self.__dict__ and attr not in self.__dict__['_constant_names_']:
    477477            self.__dict__[attr] = val
    478478            return
     
    481481        info = setters.get(attr)
    482482        if info is None:
    483             raise AttributeError, "XPCOM component '%s' can not set attribute '%s'" % (self._object_name_, attr)
     483            raise AttributeError("XPCOM component '%s' can not set attribute '%s'" % (self._object_name_, attr))
    484484        method_index, param_infos = info
    485485        if len(param_infos)!=1: # Only expecting a single input val
    486             raise RuntimeError, "Can't set properties with this many args!"
     486            raise RuntimeError("Can't set properties with this many args!")
    487487        real_param_infos = ( param_infos, (val,) )
    488488        return XPTC_InvokeByIndex(self._comobj_, method_index, real_param_infos)
     
    527527        try:
    528528            return Component(self._comobj_.QueryReferent(iid)._comobj_, iid)
    529         except COMException, details:
     529        except COMException as details:
    530530            if details.errno != nsError.NS_ERROR_NULL_POINTER:
    531531                raise
  • trunk/src/libs/xpcom18a4/python/components.py

    r59795 r59798  
    3737
    3838# This module provides the JavaScript "components" interface
    39 import xpt
    40 import xpcom, _xpcom
     39from . import xpt
     40import xpcom
     41import xpcom._xpcom as _xpcom
    4142import xpcom.client
    4243import xpcom.server
    43 import types
    44 
    45 StringTypes = [types.StringType, types.UnicodeType]
     44
     45StringTypes = [bytes, str]
    4646
    4747def _get_good_iid(iid):
     
    7979        if self._dict_data is None:
    8080            self._dict_data = self._build_dict()
    81         return self._dict_data.keys()
     81        return list(self._dict_data.keys())
    8282    def items(self):
    8383        if self._dict_data is None:
    8484            self._dict_data = self._build_dict()
    85         return self._dict_data.items()
     85        return list(self._dict_data.items())
    8686    def values(self):
    8787        if self._dict_data is None:
    8888            self._dict_data = self._build_dict()
    89         return self._dict_data.values()
    90     def has_key(self, key):
    91         if self._dict_data is None:
    92             self._dict_data = self._build_dict()
    93         return self._dict_data.has_key(key)
     89        return list(self._dict_data.values())
     90#    def has_key(self, key):
     91#        if self._dict_data is None:
     92#            self._dict_data = self._build_dict()
     93#        return self._dict_data.has_key(key)
    9494
    9595    def __len__(self):
     
    9999
    100100    def __getattr__(self, attr):
    101         if self._dict_data is not None and self._dict_data.has_key(attr):
     101        if self._dict_data is not None and attr in self._dict_data:
    102102            return self._dict_data[attr]
    103103        return self._get_one(attr)
    104104    def __getitem__(self, item):
    105         if self._dict_data is not None and self._dict_data.has_key(item):
     105        if self._dict_data is not None and item in self._dict_data:
    106106            return self._dict_data[item]
    107107        return self._get_one(item)
     
    120120        other_iid = getattr(other, "_iidobj_", other)
    121121        return cmp(this_iid, other_iid)
     122    def __eq__(self, other):
     123        this_iid = self._iidobj_
     124        other_iid = getattr(other, "_iidobj_", other)
     125        return this_iid == other_iid
    122126    def __hash__(self):
    123127        return hash(self._iidobj_)
     
    125129        return str(self._iidobj_)
    126130    def __getitem__(self, item):
    127         raise TypeError, "components.interface objects are not subscriptable"
     131        raise TypeError("components.interface objects are not subscriptable")
    128132    def __setitem__(self, item, value):
    129         raise TypeError, "components.interface objects are not subscriptable"
     133        raise TypeError("components.interface objects are not subscriptable")
    130134    def __setattr__(self, attr, value):
    131         raise AttributeError, "Can not set attributes on components.Interface objects"
     135        raise AttributeError("Can not set attributes on components.Interface objects")
    132136    def __getattr__(self, attr):
    133137        # Support constants as attributes.
     
    139143                c[c_ob.name] = c_ob.value
    140144            _constants_by_iid_map[self._iidobj_] = c
    141         if c.has_key(attr):
     145        if attr in c:
    142146            return c[attr]
    143         raise AttributeError, "'%s' interfaces do not define a constant '%s'" % (self.name, attr)
     147        raise AttributeError("'%s' interfaces do not define a constant '%s'" % (self.name, attr))
    144148
    145149
     
    148152        try:
    149153            item = interfaceInfoManager.GetInfoForName(name)
    150         except xpcom.COMException, why:
     154        except xpcom.COMException as why:
    151155            # Present a better exception message, and give a more useful error code.
    152             import nsError
     156            from . import nsError
    153157            raise xpcom.COMException(nsError.NS_ERROR_NO_INTERFACE, "The interface '%s' does not exist" % (name,))
    154158        return _Interface(item.GetName(), item.GetIID())
     
    180184            self.clsid = rc
    181185            return rc
    182         raise AttributeError, "%s class has no attribute '%s'" % (self.contractid, attr)
     186        raise AttributeError("%s class has no attribute '%s'" % (self.contractid, attr))
    183187    def createInstance(self, iid = None):
    184188        import xpcom.client
    185189        try:
    186190            return xpcom.client.Component(self.contractid, _get_good_iid(iid))
    187         except xpcom.COMException, details:
    188             import nsError
     191        except xpcom.COMException as details:
     192            from . import nsError
    189193            # Handle "no such component" in a cleaner way for the user.
    190194            if details.errno == nsError.NS_ERROR_FACTORY_NOT_REGISTERED:
     
    219223
    220224# The ID function
    221 ID = _xpcom.IID
     225ID = _xpcom.ID
    222226
    223227# A helper to cleanup our namespace as xpcom shuts down.
  • trunk/src/libs/xpcom18a4/python/file.py

    r59795 r59798  
    156156        self.close()
    157157        if mode != "r":
    158             raise ValueError, "only 'r' mode supported'"
     158            raise ValueError("only 'r' mode supported")
    159159        io_service = components.classes["@mozilla.org/network/io-service;1"] \
    160160                        .getService(components.interfaces.nsIIOService)
     
    165165        # Mozilla asserts and starts saying "NULL POINTER" if this is wrong!
    166166        if not url_ob.scheme:
    167             raise ValueError, ("The URI '%s' is invalid (no scheme)"
     167            raise ValueError("The URI '%s' is invalid (no scheme)"
    168168                                  % (url_ob.spec,))
    169169        self.channel = io_service.newChannelFromURI(url_ob)
     
    202202            self.inputStream.init(self.fileIO)
    203203        else:
    204             raise ValueError, "Unknown mode"
     204            raise ValueError("Unknown mode")
    205205
    206206    def close(self):
     
    226226    got = got + file.read()
    227227    if got != expected:
    228         raise RuntimeError, "Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected))
     228        raise RuntimeError("Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected)))
    229229
    230230def _DoTestBufferRead(file, expected):
     
    240240        got = got + str(buffer[:num])
    241241    if got != expected:
    242         raise RuntimeError, "Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected))
     242        raise RuntimeError("Reading '%s' failed - got %d bytes, but expected %d bytes" % (file, len(got), len(expected)))
    243243
    244244def _TestLocalFile():
     
    266266        # Open the same file again for writing - this should delete the old one.
    267267        if not os.path.isfile(fname):
    268             raise RuntimeError, "The file '%s' does not exist, but we are explicitly testing create semantics when it does" % (fname,)
     268            raise RuntimeError("The file '%s' does not exist, but we are explicitly testing create semantics when it does" % (fname,))
    269269        test_file = LocalFile(fname, "w")
    270270        test_file.write(data)
     
    305305def _TestURI(url):
    306306    test_file = URIFile(url)
    307     print "Opened file is", test_file
     307    print("Opened file is", test_file)
    308308    got = test_file.read()
    309     print "Read %d bytes of data from %r" % (len(got), url)
     309    print("Read %d bytes of data from %r" % (len(got), url))
    310310    test_file.close()
    311311
     
    313313    import sys
    314314    if len(sys.argv) < 2:
    315         print "No URL specified on command line - performing self-test"
     315        print("No URL specified on command line - performing self-test")
    316316        _TestAll()
    317317    else:
  • trunk/src/libs/xpcom18a4/python/gen_python_deps.py

    r59795 r59798  
    22
    33"""
    4 Copyright (C) 2009-2013 Oracle Corporation
     4Copyright (C) 2009-2016 Oracle Corporation
    55
    66This file is part of VirtualBox Open Source Edition (OSE), as
     
    1414
    1515import os,sys
     16from distutils.version import StrictVersion
    1617
    17 versions = ["2.3", "2.4", "2.5", "2.6", "2.7",]
     18versions = ["2.6", "2.7", "3.1", "3.2", "3.3", "3.4", "3.5"]
    1819prefixes = ["/usr", "/usr/local", "/opt", "/opt/local"]
    1920known = {}
     
    4142
    4243def print_vars(vers, known, sep, bitness_magic):
    43     print "VBOX_PYTHON%s_INC=%s%s" %(vers, known[0], sep)
     44    print("VBOX_PYTHON%s_INC=%s%s" %(vers, known[0], sep))
    4445    if bitness_magic > 0:
    45         print "VBOX_PYTHON%s_LIB=%s%s" %(vers, known[2], sep)
    46         print "VBOX_PYTHON%s_LIB_X86=%s%s" %(vers, known[1], sep)
     46        print("VBOX_PYTHON%s_LIB=%s%s" %(vers, known[2], sep))
     47        print("VBOX_PYTHON%s_LIB_X86=%s%s" %(vers, known[1], sep))
    4748    else:
    48         print "VBOX_PYTHON%s_LIB=%s%s" %(vers, known[1], sep)
     49        print("VBOX_PYTHON%s_LIB=%s%s" %(vers, known[1], sep))
    4950
    5051
     
    9192
    9293    for v in versions:
     94        if StrictVersion(v) < StrictVersion('2.6'):
     95            continue
    9396        for p in prefixes:
    9497            c = checkPair(p, v, dllpre, dllsuff, bitness_magic)
     
    9699                known[v] = c
    97100                break
    98     keys = known.keys()
     101    keys = list(known.keys())
    99102    # we want default to be the lowest versioned Python
    100103    keys.sort()
  • trunk/src/libs/xpcom18a4/python/primitives.py

    r59795 r59798  
    3535        better = _primitives_map[prin.type]
    3636    except KeyError:
    37         raise ValueError, "This primitive type (%d) is not supported" % (prin.type,)
     37        raise ValueError("This primitive type (%d) is not supported" % (prin.type,))
    3838    prin = prin.QueryInterface(better)
    3939    return prin.data
  • trunk/src/libs/xpcom18a4/python/server/__init__.py

    r59795 r59798  
    3838# The xpcom.server package.
    3939
    40 from policy import DefaultPolicy
     40from xpcom.server.policy import DefaultPolicy
    4141from xpcom import _xpcom
    4242
     
    8080# Python!
    8181def NS_GetModule( serviceManager, nsIFile ):
    82     import loader
     82    from . import loader
    8383    iid = _xpcom.IID_nsIModule
    8484    return WrapObject(loader.MakePythonComponentLoaderModule(serviceManager, nsIFile), iid, bWrapClient = 0)
    8585
    8686def _shutdown():
    87     from policy import _shutdown
     87    from server.policy import _shutdown
    8888    _shutdown()
  • trunk/src/libs/xpcom18a4/python/server/loader.py

    r59795 r59798  
    3838import xpcom
    3939from xpcom import components, logger
    40 
    41 import module
    42 
    43 import glob, os, types
    44 
     40from . import module
     41import glob
     42import os
    4543from xpcom.client import Component
    4644
     
    5755    # For now, just run over all classes looking for likely candidates.
    5856    comps = []
    59     for name, object in py_module.__dict__.items():
     57    for name, object in list(py_module.__dict__.items()):
    6058        try:
    61             if (type(object) == types.ClassType or issubclass(object, object)) and \
     59            if (type(object) == type or issubclass(object, object)) and \
    6260               _has_good_attr(object, "_com_interfaces_") and \
    6361               _has_good_attr(object, "_reg_clsid_") and \
     
    148146                    self.autoRegisterComponent(when, entry)
    149147                # Handle some common user errors
    150                 except xpcom.COMException, details:
     148                except xpcom.COMException as details:
    151149                    from xpcom import nsError
    152150                    # If the interface name does not exist, suppress the traceback
     
    156154                    else:
    157155                        logger.exception("Registration of '%s' failed!", entry.leafName)
    158                 except SyntaxError, details:
     156                except SyntaxError as details:
    159157                    # Syntax error in source file - no useful traceback here either.
    160158                    logger.error("Registration of '%s' failed\n %s",
     
    226224
    227225def MakePythonComponentLoaderModule(serviceManager, nsIFile):
    228     import module
     226    from . import module
    229227    return module.Module( [PythonComponentLoader] )
  • trunk/src/libs/xpcom18a4/python/server/module.py

    r59795 r59798  
    3939from xpcom import nsError
    4040
    41 import factory
     41from . import factory
    4242
    4343import types
     
    6666        # void function.
    6767        fname = os.path.basename(location.path)
    68         for klass in self.components.values():
     68        for klass in list(self.components.values()):
    6969            reg_contractid = klass._reg_contractid_
    70             print "Registering '%s' (%s)" % (reg_contractid, fname)
     70            print("Registering '%s' (%s)" % (reg_contractid, fname))
    7171            reg_desc = getattr(klass, "_reg_desc_", reg_contractid)
    7272            compMgr = compMgr.queryInterface(components.interfaces.nsIComponentRegistrar)
     
    8585    def unregisterSelf(self, compMgr, location, loaderStr):
    8686        # void function.
    87         for klass in self.components.values():
     87        for klass in list(self.components.values()):
    8888            ok = 1
    8989            try:
     
    9999                    ok = 0
    100100            if ok:
    101                 print "Successfully unregistered", klass.__name__
     101                print("Successfully unregistered", klass.__name__)
    102102            else:
    103                 print "Unregistration of", klass.__name__, "failed. (probably just not already registered)"
     103                print("Unregistration of", klass.__name__, "failed. (probably just not already registered)")
    104104       
    105105    def canUnload(self, compMgr):
  • trunk/src/libs/xpcom18a4/python/server/policy.py

    r59795 r59798  
    4343import types
    4444import logging
     45import sys
    4546
    4647
     
    6162_supports_primitives_map_ = {} # Filled on first use.
    6263
    63 _interface_sequence_types_ = types.TupleType, types.ListType
    64 _string_types_ = types.StringType, types.UnicodeType
     64_interface_sequence_types_ = tuple, list
     65if sys.version_info[0] <= 2:
     66    _string_types_ = str, unicode
     67else:
     68    _string_types_ = bytes, str
    6569XPTI_GetInterfaceInfoManager = _xpcom.XPTI_GetInterfaceInfoManager
    6670
     
    142146        self._iid_ = iid
    143147        if ni is None:
    144             raise ValueError, "The object '%r' can not be used as a COM object" % (instance,)
     148            raise ValueError("The object '%r' can not be used as a COM object" % (instance,))
    145149        # This is really only a check for the user
    146150        if __debug__:
     
    286290            if logger.isEnabledFor(logging.DEBUG):
    287291                try:
    288                     raise exc_info[0], exc_info[1], exc_info[2]
     292                    raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
    289293                except:
    290294                    logger.debug("'%s' raised COM Exception %s",
     
    294298        # As above, trick the logging module to handle Python 2.3
    295299        try:
    296             raise exc_info[0], exc_info[1], exc_info[2]
     300            raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
    297301        except:
    298302            logger.exception("Unhandled exception calling '%s'", func_name)
     
    331335_supports_primitives_data_ = [
    332336    ("nsISupportsCString", "__str__", str),
    333     ("nsISupportsString", "__unicode__", unicode),
    334     ("nsISupportsPRUint64", "__long__", long),
    335     ("nsISupportsPRInt64", "__long__", long),
     337    ("nsISupportsString", "__unicode__", str),
     338    ("nsISupportsPRUint64", "__long__", int),
     339    ("nsISupportsPRInt64", "__long__", int),
    336340    ("nsISupportsPRUint32", "__int__", int),
    337341    ("nsISupportsPRInt32", "__int__", int),
  • trunk/src/libs/xpcom18a4/python/src/PyXPCOM.h

    r59795 r59798  
    133133# endif
    134134
     135# if PY_MAJOR_VERSION >= 3
     136#  define PyInt_FromLong(l) PyLong_FromLong(l)
     137#  define PyInt_Check(o) PyLong_Check(o)
     138#  define PyInt_AsLong(o) PyLong_AsLong(o)
     139#  define PyNumber_Int(o) PyNumber_Long(o)
     140#  ifndef PyUnicode_AsUTF8
     141#   define PyUnicode_AsUTF8(o) _PyUnicode_AsString(o)
     142#  endif
     143#  ifndef PyUnicode_AsUTF8AndSize
     144#   define PyUnicode_AsUTF8AndSize(o,s) _PyUnicode_AsStringAndSize(o,s)
     145#  endif
     146typedef struct PyMethodChain
     147{
     148    PyMethodDef *methods;
     149    struct PyMethodChain *link;
     150} PyMethodChain;
     151# endif
     152
    135153#endif /* VBOX_PYXPCOM */
    136154
     
    268286        static int Py_setattr(PyObject *op, char *name, PyObject *v);
    269287        static int Py_cmp(PyObject *ob1, PyObject *ob2);
     288        static PyObject *Py_richcmp(PyObject *ob1, PyObject *ob2, int op);
    270289        static long Py_hash(PyObject *self);
    271290};
     
    419438        /* Python support */
    420439        static PyObject *PyTypeMethod_getattr(PyObject *self, char *name);
     440#if PY_MAJOR_VERSION <= 2
    421441        static int PyTypeMethod_compare(PyObject *self, PyObject *ob);
     442#endif
     443        static PyObject *PyTypeMethod_richcompare(PyObject *self, PyObject *ob, int op);
    422444        static PyObject *PyTypeMethod_repr(PyObject *self);
    423445        static long PyTypeMethod_hash(PyObject *self);
  • trunk/src/libs/xpcom18a4/python/test/test_test_component.py

    r59795 r59798  
    253253    test_attribute(c, "iid_value", component_iid, new_iid)
    254254    test_attribute(c, "iid_value", component_iid, str(new_iid), new_iid)
    255     test_attribute(c, "iid_value", component_iid, xpcom._xpcom.IID(new_iid))
     255    test_attribute(c, "iid_value", component_iid, xpcom._xpcom.ID(new_iid))
    256256
    257257    test_attribute_failure(c, "no_attribute", "boo", AttributeError)
  • trunk/src/libs/xpcom18a4/python/vboxxpcom.py

    r59795 r59798  
    11"""
    2 Copyright (C) 2008-2012 Oracle Corporation
     2Copyright (C) 2008-2016 Oracle Corporation
    33
    44This file is part of VirtualBox Open Source Edition (OSE), as
     
    4747        _oVBoxPythonMod =  __import__(m)
    4848        break
    49     except Exception, x:
    50         print 'm=%s x=%s' % (m, x);
     49    except Exception as x:
     50        print('m=%s x=%s' % (m, x))
    5151    #except:
    5252    #    pass
  • trunk/src/libs/xpcom18a4/python/xpt.py

    r59795 r59798  
    7272import xpcom._xpcom
    7373
    74 from xpcom_consts import *
     74from .xpcom_consts import *
    7575
    7676class Interface:
     
    100100            if xpcom.verbose:
    101101                # The user may be confused as to why this is happening!
    102                 print "The parent interface of IID '%s' can not be located - assuming nsISupports"
     102                print("The parent interface of IID '%s' can not be located - assuming nsISupports")
    103103            return Interface(xpcom._xpcom.IID_nsISupports)
    104104
    105105    def Describe_Python(self):
    106106        method_reprs = []
    107         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
     107        methods = [m for m in self.methods if not m.IsNotXPCOM()]
    108108        for m in methods:
    109109            method_reprs.append(m.Describe_Python())
     
    130130        s = s + '         Scriptable: ' + word + '\n'
    131131        s = s + '      Methods:\n'
    132         methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
     132        methods = [m for m in self.methods if not m.IsNotXPCOM()]
    133133        if len(methods):
    134134            for m in methods:
     
    153153        except xpcom.Exception:
    154154            if xpcom.verbose:
    155                 print "** GetMethodCount failed?? - assuming no methods"
     155                print("** GetMethodCount failed?? - assuming no methods")
    156156            self.items = []
    157157    def __len__(self):
     
    252252
    253253        def desc(a): return a.Describe()
    254         method_desc = string.join(map(desc, self.params), ', ')
     254        method_desc = string.join(list(map(desc, self.params)), ', ')
    255255        result_type = TypeDescriber(self.result_desc[0], None)
    256256        return_desc = result_type.Describe()
     
    329329        except xpcom.Exception:
    330330            if xpcom.verbose:
    331                 print "** GetConstantCount failed?? - assuming no constants"
     331                print("** GetConstantCount failed?? - assuming no constants")
    332332            self.items = []
    333333    def __len__(self):
     
    452452        describer_name = describer_name + "_" + mode.capitalize()
    453453    describer = getattr(interface, describer_name)
    454     print describer()
     454    print(describer())
    455455
    456456if __name__=='__main__':
    457457    if len(sys.argv) == 1:
    458         print "Usage: xpt.py [-xptinfo] interface_name, ..."
    459         print "  -info: Dump in a style similar to the xptdump tool"
    460         print "Dumping nsISupports and nsIInterfaceInfo"
     458        print("Usage: xpt.py [-xptinfo] interface_name, ...")
     459        print("  -info: Dump in a style similar to the xptdump tool")
     460        print("Dumping nsISupports and nsIInterfaceInfo")
    461461        sys.argv.append('nsIInterfaceInfo')
    462462        sys.argv.append('-xptinfo')
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