Changeset 59795 in vbox
- Timestamp:
- Feb 24, 2016 9:13:27 AM (9 years ago)
- Location:
- trunk
- Files:
-
- 37 edited
-
Config.kmk (modified) (1 diff)
-
doc/manual/en_US/SDKRef.xml (modified) (3 diffs)
-
src/VBox/Frontends/VBoxShell/vboxshell.py (modified) (186 diffs)
-
src/VBox/Installer/common/vboxapisetup.py (modified) (2 diffs)
-
src/VBox/Main/glue/vboxapi.py (modified) (3 diffs)
-
src/VBox/Main/webservice/websrv-python.xsl (modified) (17 diffs)
-
src/VBox/ValidationKit/testdriver/vbox.py (modified) (1 diff)
-
src/libs/xpcom18a4/python/Makefile.kmk (modified) (5 diffs)
-
src/libs/xpcom18a4/python/__init__.py (modified) (7 diffs)
-
src/libs/xpcom18a4/python/client/__init__.py (modified) (19 diffs)
-
src/libs/xpcom18a4/python/components.py (modified) (9 diffs)
-
src/libs/xpcom18a4/python/file.py (modified) (8 diffs)
-
src/libs/xpcom18a4/python/gen_python_deps.py (modified) (5 diffs)
-
src/libs/xpcom18a4/python/primitives.py (modified) (1 diff)
-
src/libs/xpcom18a4/python/server/__init__.py (modified) (2 diffs)
-
src/libs/xpcom18a4/python/server/loader.py (modified) (5 diffs)
-
src/libs/xpcom18a4/python/server/module.py (modified) (4 diffs)
-
src/libs/xpcom18a4/python/server/policy.py (modified) (6 diffs)
-
src/libs/xpcom18a4/python/src/ErrorUtils.cpp (modified) (6 diffs)
-
src/libs/xpcom18a4/python/src/PyGBase.cpp (modified) (17 diffs)
-
src/libs/xpcom18a4/python/src/PyIClassInfo.cpp (modified) (2 diffs)
-
src/libs/xpcom18a4/python/src/PyIComponentManagerObsolete.cpp (modified) (2 diffs)
-
src/libs/xpcom18a4/python/src/PyIID.cpp (modified) (12 diffs)
-
src/libs/xpcom18a4/python/src/PyIInputStream.cpp (modified) (3 diffs)
-
src/libs/xpcom18a4/python/src/PyIInterfaceInfo.cpp (modified) (2 diffs)
-
src/libs/xpcom18a4/python/src/PyIInterfaceInfoManager.cpp (modified) (2 diffs)
-
src/libs/xpcom18a4/python/src/PyISupports.cpp (modified) (1 diff)
-
src/libs/xpcom18a4/python/src/PyIVariant.cpp (modified) (3 diffs)
-
src/libs/xpcom18a4/python/src/PyXPCOM.h (modified) (3 diffs)
-
src/libs/xpcom18a4/python/src/Pyxpt_info.cpp (modified) (5 diffs)
-
src/libs/xpcom18a4/python/src/TypeObject.cpp (modified) (11 diffs)
-
src/libs/xpcom18a4/python/src/VariantUtils.cpp (modified) (50 diffs)
-
src/libs/xpcom18a4/python/src/dllmain.cpp (modified) (5 diffs)
-
src/libs/xpcom18a4/python/src/module/_xpcom.cpp (modified) (16 diffs)
-
src/libs/xpcom18a4/python/test/test_test_component.py (modified) (1 diff)
-
src/libs/xpcom18a4/python/vboxxpcom.py (modified) (2 diffs)
-
src/libs/xpcom18a4/python/xpt.py (modified) (7 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/Config.kmk
r59790 r59795 6474 6474 $(MAKE) VBOX_QUICK=1 6475 6475 6476 -
trunk/doc/manual/en_US/SDKRef.xml
r59771 r59795 781 781 <xref linkend="glue-python"/>.</para> 782 782 783 <para>The minimum supported Python version is 2.6.</para>784 785 783 <para>As indicated in <xref linkend="webservice-or-com"/>, the 786 784 COM/XPCOM API gives better performance without the SOAP overhead, and … … 790 788 platform<footnote> 791 789 <para>On On Mac OS X only the Python versions bundled with the OS 792 are officially supported. This means 2.6 and 2.7 for 10.8 and later.</para> 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> 793 792 </footnote>). On Windows, you can use the Main API from Python if the 794 793 Win32 extensions package for Python<footnote> 795 794 <para>See <ulink 796 795 url="http://sourceforge.net/project/showfiles.php?group_id=78018">http://sourceforge.net/project/showfiles.php?group_id=78018</ulink>.</para> 797 </footnote> is installed. Version sof Python Win32 extensions earlier796 </footnote> is installed. Version of Python Win32 extensions earlier 798 797 than 2.16 are known to have bugs, leading to issues with VirtualBox 799 Python bindings, so please make sure to use latest available Python 800 and Win32 extensions.</para> 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> 801 802 802 803 <para>The VirtualBox OOWS for Python relies on the Python ZSI SOAP … … 1496 1497 the glue layer if you want to use a different Python 1497 1498 installation.</para> 1498 1499 <para>The minimum supported Python version is 2.6.</para>1500 1499 1501 1500 <para>In this layer, the class -
trunk/src/VBox/Frontends/VBoxShell/vboxshell.py
r59777 r59795 2 2 # -*- coding: utf-8 -*- 3 3 # $Id$ 4 5 4 """ 6 5 VirtualBox Python Shell. … … 20 19 """ 21 20 22 from __future__ import print_function23 24 21 __copyright__ = \ 25 22 """ 26 Copyright (C) 2009-201 6Oracle Corporation23 Copyright (C) 2009-2015 Oracle Corporation 27 24 28 25 This file is part of VirtualBox Open Source Edition (OSE), as … … 37 34 38 35 39 import os 40 import sys 36 import os, sys 41 37 import traceback 42 38 import shlex … … 46 42 from optparse import OptionParser 47 43 from pprint import pprint 44 48 45 49 46 … … 155 152 matches.append(word) 156 153 157 except Exception ase:154 except Exception, e: 158 155 printErr(self.ctx, e) 159 156 if g_fVerbose: … … 167 164 168 165 comps = {} 169 for (key, _value) in list(cmds.items()):166 for (key, _value) in cmds.items(): 170 167 comps[key] = None 171 168 completer = CompleterNG(comps, ctx) … … 192 189 try: 193 190 while not progress.completed: 194 print ("%s %%\r" % (colored(str(progress.percent), 'red')), end="")191 print "%s %%\r" % (colored(str(progress.percent), 'red')), 195 192 sys.stdout.flush() 196 193 progress.waitForCompletion(wait) … … 200 197 return 1 201 198 except KeyboardInterrupt: 202 print ("Interrupted.")199 print "Interrupted." 203 200 ctx['interrupt'] = True 204 201 if progress.cancelable: 205 print ("Canceling task...")202 print "Canceling task..." 206 203 progress.cancel() 207 204 return 0 208 205 209 206 def printErr(_ctx, e): 210 oVBoxMgr = _ctx['global'] 207 oVBoxMgr = _ctx['global']; 211 208 if oVBoxMgr.errIsOurXcptKind(e): 212 print (colored('%s: %s' % (oVBoxMgr.xcptToString(e), oVBoxMgr.xcptGetMessage(e)), 'red'))213 else: 214 print (colored(str(e), 'red'))209 print colored('%s: %s' % (oVBoxMgr.xcptToString(e), oVBoxMgr.xcptGetMessage(e)), 'red'); 210 else: 211 print colored(str(e), 'red') 215 212 216 213 def reportError(_ctx, progress): 217 214 errorinfo = progress.errorInfo 218 215 if errorinfo: 219 print (colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red'))216 print colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red') 220 217 221 218 def colCat(_ctx, strg): … … 244 241 mach = vbox.createMachine("", name, [], kind, "") 245 242 mach.saveSettings() 246 print ("created machine with UUID", mach.id)243 print "created machine with UUID", mach.id 247 244 vbox.registerMachine(mach) 248 245 # update cache … … 251 248 def removeVm(ctx, mach): 252 249 uuid = mach.id 253 print ("removing machine ", mach.name, "with UUID", uuid)250 print "removing machine ", mach.name, "with UUID", uuid 254 251 cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"]) 255 252 disks = mach.unregister(ctx['global'].constants.CleanupMode_Full) … … 257 254 progress = mach.deleteConfig(disks) 258 255 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0: 259 print ("Success!")256 print "Success!" 260 257 else: 261 258 reportError(ctx, progress) … … 274 271 try: 275 272 perf.setup(['*'], [mach], 10, 15) 276 except Exception ase:273 except Exception, e: 277 274 printErr(ctx, e) 278 275 if g_fVerbose: … … 327 324 return 328 325 for metric in ctx['perf'].query(["*"], [mach]): 329 print (metric['name'], metric['values_as_string'])326 print metric['name'], metric['values_as_string'] 330 327 331 328 def guestExec(ctx, machine, console, cmds): 332 exec (cmds)329 exec cmds 333 330 334 331 def printMouseEvent(_ctx, mev): 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))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) 336 333 337 334 def printKbdEvent(ctx, kev): 338 print ("Kbd: ", ctx['global'].getArray(kev, 'scancodes'))335 print "Kbd: ", ctx['global'].getArray(kev, 'scancodes') 339 336 340 337 def printMultiTouchEvent(ctx, mtev): 341 print ("MultiTouch : contacts=%d time=%d" % (mtev.contactCount, mtev.scanTime))338 print "MultiTouch : contacts=%d time=%d" % (mtev.contactCount, mtev.scanTime) 342 339 xPositions = ctx['global'].getArray(mtev, 'xPositions') 343 340 yPositions = ctx['global'].getArray(mtev, 'yPositions') … … 346 343 347 344 for i in range(0, mtev.contactCount): 348 print (" [%d] %d,%d %d %d" % (i, xPositions[i], yPositions[i], contactIds[i], contactFlags[i]))345 print " [%d] %d,%d %d %d" % (i, xPositions[i], yPositions[i], contactIds[i], contactFlags[i]) 349 346 350 347 def monitorSource(ctx, eventSource, active, dur): 351 348 def handleEventImpl(event): 352 349 evtype = event.type 353 print ("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))350 print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)) 354 351 if evtype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged: 355 352 scev = ctx['global'].queryInterface(event, 'IMachineStateChangedEvent') 356 353 if scev: 357 print ("machine state event: mach=%s state=%s" % (scev.machineId, scev.state))354 print "machine state event: mach=%s state=%s" % (scev.machineId, scev.state) 358 355 elif evtype == ctx['global'].constants.VBoxEventType_OnSnapshotTaken: 359 356 stev = ctx['global'].queryInterface(event, 'ISnapshotTakenEvent') 360 357 if stev: 361 print ("snapshot taken event: mach=%s snap=%s" % (stev.machineId, stev.snapshotId))358 print "snapshot taken event: mach=%s snap=%s" % (stev.machineId, stev.snapshotId) 362 359 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged: 363 360 gpcev = ctx['global'].queryInterface(event, 'IGuestPropertyChangedEvent') 364 361 if gpcev: 365 print ("guest property change: name=%s value=%s" % (gpcev.name, gpcev.value))362 print "guest property change: name=%s value=%s" % (gpcev.name, gpcev.value) 366 363 elif evtype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged: 367 364 psev = ctx['global'].queryInterface(event, 'IMousePointerShapeChangedEvent') … … 369 366 shape = ctx['global'].getArray(psev, 'shape') 370 367 if shape is None: 371 print ("pointer shape event - empty shape")368 print "pointer shape event - empty shape" 372 369 else: 373 print ("pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape)))370 print "pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape)) 374 371 elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse: 375 372 mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent') … … 444 441 def handleEventImpl(event): 445 442 evtype = event.type 446 #print ("got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)))443 #print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype)) 447 444 if evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse: 448 445 mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent') … … 492 489 493 490 header = demo.readline() 494 print ("Header is", header)491 print "Header is", header 495 492 basere = re.compile(r'(?P<s>\d+): (?P<t>[km]) (?P<p>.*)') 496 493 mre = re.compile(r'(?P<a>\d+) (?P<x>-*\d+) (?P<y>-*\d+) (?P<z>-*\d+) (?P<w>-*\d+) (?P<b>-*\d+)') … … 518 515 if rtype == 'k': 519 516 codes = kre.findall(params) 520 #print ("KBD:", codes)517 #print "KBD:", codes 521 518 kbd.putScancodes(codes) 522 519 elif rtype == 'm': … … 526 523 if mdict['a'] == '1': 527 524 # absolute 528 #print ("MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b'])525 #print "MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b'] 529 526 mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 530 527 else: 531 #print ("MR: ", mdict['x'], mdict['y'], mdict['b'])528 #print "MR: ", mdict['x'], mdict['y'], mdict['b'] 532 529 mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b'])) 533 530 … … 562 559 h = fbh 563 560 564 print ("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))561 print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f) 565 562 data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_RGBA) 566 563 size = (w, h) … … 589 586 h = fbh 590 587 591 print ("Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f))588 print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f) 592 589 data = display.takeScreenShotToArray(screen, w, h, ctx['const'].BitmapFormat_PNG) 593 590 pngfile = open(f, 'wb') … … 597 594 def teleport(ctx, _session, console, args): 598 595 if args[0].find(":") == -1: 599 print ("Use host:port format for teleport target")596 print "Use host:port format for teleport target" 600 597 return 601 598 (host, port) = args[0].split(":") … … 611 608 612 609 port = int(port) 613 print ("Teleporting to %s:%d..." % (host, port))610 print "Teleporting to %s:%d..." % (host, port) 614 611 progress = console.teleport(host, port, passwd, maxDowntime) 615 612 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0: 616 print ("Success!")613 print "Success!" 617 614 else: 618 615 reportError(ctx, progress) … … 635 632 all_stats = ctx['const'].all_values('GuestStatisticType') 636 633 cpu = 0 637 for s in list(all_stats.keys()):634 for s in all_stats.keys(): 638 635 try: 639 636 val = guest.getStatistic( cpu, all_stats[s]) 640 print ("%s: %d" % (s, val))637 print "%s: %d" % (s, val) 641 638 except: 642 639 # likely not implemented … … 645 642 def plugCpu(_ctx, machine, _session, args): 646 643 cpu = int(args[0]) 647 print ("Adding CPU %d..." % (cpu))644 print "Adding CPU %d..." % (cpu) 648 645 machine.hotPlugCPU(cpu) 649 646 650 647 def unplugCpu(_ctx, machine, _session, args): 651 648 cpu = int(args[0]) 652 print ("Removing CPU %d..." % (cpu))649 print "Removing CPU %d..." % (cpu) 653 650 machine.hotUnplugCPU(cpu) 654 651 … … 664 661 665 662 def printHostUsbDev(ctx, ud): 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)))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)) 667 664 668 665 def printUsbDev(_ctx, ud): 669 print (" %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber))666 print " %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id, colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber) 670 667 671 668 def printSf(ctx, sf): 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")))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")) 673 670 674 671 def ginfo(ctx, console, _args): 675 672 guest = console.guest 676 673 if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None: 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")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" 684 681 usbs = ctx['global'].getArray(console, 'USBDevices') 685 print ("Attached USB:")682 print "Attached USB:" 686 683 for ud in usbs: 687 684 printUsbDev(ctx, ud) 688 685 rusbs = ctx['global'].getArray(console, 'remoteUSBDevices') 689 print ("Remote USB:")686 print "Remote USB:" 690 687 for ud in rusbs: 691 688 printHostUsbDev(ctx, ud) 692 print ("Transient shared folders:")689 print "Transient shared folders:" 693 690 sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders') 694 691 for sf in sfs: … … 701 698 session = ctx['global'].getSessionObject(vbox) 702 699 mach.lockMachine(session, ctx['global'].constants.LockType_Shared) 703 except Exception ase:700 except Exception, e: 704 701 printErr(ctx, "Session to '%s' not open: %s" % (mach.name, str(e))) 705 702 if g_fVerbose: … … 707 704 return 708 705 if session.state != ctx['const'].SessionState_Locked: 709 print ("Session to '%s' in wrong state: %s" % (mach.name, session.state))706 print "Session to '%s' in wrong state: %s" % (mach.name, session.state) 710 707 session.unlockMachine() 711 708 return … … 713 710 # in Webservices) functionality 714 711 if ctx['remote'] and cmd == 'some_local_only_command': 715 print ('Trying to use local only functionality, ignored')712 print 'Trying to use local only functionality, ignored' 716 713 session.unlockMachine() 717 714 return … … 737 734 except KeyboardInterrupt: 738 735 ctx['interrupt'] = True 739 except Exception ase:736 except Exception, e: 740 737 printErr(ctx, e) 741 738 if g_fVerbose: … … 750 747 try: 751 748 cmd(ctx, mach, args) 752 except Exception ase:749 except Exception, e: 753 750 save = False 754 751 printErr(ctx, e) … … 758 755 try: 759 756 mach.saveSettings() 760 except Exception ase:757 except Exception, e: 761 758 printErr(ctx, e) 762 759 if g_fVerbose: … … 770 767 try: 771 768 cmd(ctx, mach, session.console, args) 772 except Exception ase:769 except Exception, e: 773 770 save = False 774 771 printErr(ctx, e) … … 780 777 781 778 def machById(ctx, uuid): 782 mach = ctx['vb'].findMachine(uuid) 779 try: 780 mach = ctx['vb'].getMachine(uuid) 781 except: 782 mach = ctx['vb'].findMachine(uuid) 783 783 return mach 784 784 … … 899 899 def argsToMach(ctx, args): 900 900 if len(args) < 2: 901 print ("usage: %s [vmname|uuid]" % (args[0]))901 print "usage: %s [vmname|uuid]" % (args[0]) 902 902 return None 903 903 uuid = args[1] 904 904 mach = machById(ctx, uuid) 905 905 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) 907 907 return mach 908 908 … … 912 912 else: 913 913 spec = "" 914 print (" %s: %s%s" % (colored(cmd, 'blue'), h, spec))914 print " %s: %s%s" % (colored(cmd, 'blue'), h, spec) 915 915 916 916 def helpCmd(_ctx, args): 917 917 if len(args) == 1: 918 print ("Help page:")919 names = list(commands.keys())918 print "Help page:" 919 names = commands.keys() 920 920 names.sort() 921 921 for i in names: … … 925 925 c = commands.get(cmd) 926 926 if c == None: 927 print ("Command '%s' not known" % (cmd))927 print "Command '%s' not known" % (cmd) 928 928 else: 929 929 helpSingleCmd(cmd, c[0], c[2]) … … 932 932 def asEnumElem(ctx, enum, elem): 933 933 enumVals = ctx['const'].all_values(enum) 934 for e in list(enumVals.keys()):934 for e in enumVals.keys(): 935 935 if str(elem) == str(enumVals[e]): 936 936 return colored(e, 'green') … … 948 948 else: 949 949 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 ase: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: 952 952 printErr(ctx, e) 953 953 if g_fVerbose: … … 956 956 957 957 def 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]" 960 960 return 0 961 961 mach = argsToMach(ctx, args) … … 963 963 return 0 964 964 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 981 981 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 984 984 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)) 987 987 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) 989 989 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) 991 991 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)) 999 999 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(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(long(mach.lastStateChange)/1000)) 1006 1006 # OSE has no VRDE 1007 1007 try: 1008 print (" VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled)))1008 print " VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled)) 1009 1009 except: 1010 1010 pass 1011 1011 1012 print ()1013 print (colCat(ctx, " USB Controllers:"))1012 print 1013 print colCat(ctx, " USB Controllers:") 1014 1014 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) 1022 1022 1023 1023 controllers = ctx['global'].getArray(mach, 'storageControllers') 1024 1024 if controllers: 1025 print ()1026 print (colCat(ctx, " Storage Controllers:"))1025 print 1026 print colCat(ctx, " Storage Controllers:") 1027 1027 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)) 1029 1029 1030 1030 attaches = ctx['global'].getArray(mach, 'mediumAttachments') 1031 1031 if attaches: 1032 print ()1033 print (colCat(ctx, " Media:"))1032 print 1033 print colCat(ctx, " Media:") 1034 1034 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) 1036 1036 medium = a.medium 1037 1037 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) 1043 1043 1044 1044 if a.type == ctx['global'].constants.DeviceType_DVD: 1045 print (" DVD:")1045 print " DVD:" 1046 1046 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) 1049 1049 if medium.hostDrive: 1050 print (" Host DVD %s" % (colPath(ctx, medium.location)))1050 print " Host DVD %s" % (colPath(ctx, medium.location)) 1051 1051 if a.passthrough: 1052 print (" [passthrough mode]")1052 print " [passthrough mode]" 1053 1053 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) 1056 1056 1057 1057 if a.type == ctx['global'].constants.DeviceType_Floppy: 1058 print (" Floppy:")1058 print " Floppy:" 1059 1059 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) 1062 1062 if medium.hostDrive: 1063 print (" Host floppy %s" % (colPath(ctx, medium.location)))1063 print " Host floppy %s" % (colPath(ctx, medium.location)) 1064 1064 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:") 1070 1070 for sf in ctx['global'].getArray(mach, 'sharedFolders'): 1071 1071 printSf(ctx, sf) … … 1075 1075 def startCmd(ctx, args): 1076 1076 if len(args) < 2: 1077 print ("usage: start name <frontend>")1077 print "usage: start name <frontend>" 1078 1078 return 0 1079 1079 mach = argsToMach(ctx, args) … … 1088 1088 1089 1089 def 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" 1092 1092 return 0 1093 1093 name = args[1] … … 1096 1096 ctx['vb'].getGuestOSType(oskind) 1097 1097 except Exception: 1098 print ('Unknown OS type:', oskind)1098 print 'Unknown OS type:', oskind 1099 1099 return 0 1100 1100 createVm(ctx, name, oskind) … … 1102 1102 1103 1103 def 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]" 1106 1106 return 0 1107 1107 mach = argsToMach(ctx, args) … … 1113 1113 def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None): 1114 1114 if len(args) < 1: 1115 print ("exec in guest needs at least program name")1115 print "exec in guest needs at least program name" 1116 1116 return 1117 1117 guest = console.guest … … 1119 1119 # shall contain program name as argv[0] 1120 1120 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) 1122 1122 flags = 0 1123 1123 if inputPipe is not None: 1124 1124 flags = 1 # set WaitForProcessStartOnly 1125 print (args[0])1125 print args[0] 1126 1126 process = guestSession.processCreate(args[0], gargs, env, [], tmo) 1127 print ("executed with pid %d" % (process.PID))1127 print "executed with pid %d" % (process.PID) 1128 1128 if pid != 0: 1129 1129 try: … … 1161 1161 1162 1162 except KeyboardInterrupt: 1163 print ("Interrupted.")1163 print "Interrupted." 1164 1164 ctx['interrupt'] = True 1165 1165 if progress.cancelable: 1166 1166 progress.cancel() 1167 1167 (_reason, code, _flags) = guest.getProcessStatus(pid) 1168 print ("Exit code: %d" % (code))1168 print "Exit code: %d" % (code) 1169 1169 return 0 1170 1170 else: … … 1175 1175 dst = args[1] 1176 1176 flags = 0 1177 print ("Copying host %s to guest %s" % (src, dst))1177 print "Copying host %s to guest %s" % (src, dst) 1178 1178 progress = console.guest.copyToGuest(src, dst, user, passwd, flags) 1179 1179 progressBar(ctx, progress) … … 1196 1196 user = getpass.getuser() 1197 1197 user_inp = nh_raw_input("User (%s): " % (user)) 1198 if len (user_inp) > 0:1198 if len (user_inp) > 0: 1199 1199 user = user_inp 1200 1200 passwd = getpass.getpass() … … 1203 1203 1204 1204 def 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" 1207 1207 return 0 1208 1208 mach = argsToMach(ctx, args) … … 1217 1217 1218 1218 def 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" 1221 1221 return 0 1222 1222 mach = argsToMach(ctx, args) … … 1236 1236 1237 1237 def 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\"'" 1240 1240 return 0 1241 1241 mach = argsToMach(ctx, args) … … 1309 1309 1310 1310 def 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" 1313 1313 return 0 1314 1314 mach = argsToMach(ctx, args) … … 1322 1322 1323 1323 def 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>" 1326 1326 return 0 1327 1327 mach = argsToMach(ctx, args) … … 1332 1332 1333 1333 def 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>" 1336 1336 return 0 1337 1337 mach = argsToMach(ctx, args) … … 1351 1351 1352 1352 def 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>" 1355 1355 return 0 1356 1356 mach = argsToMach(ctx, args) … … 1358 1358 return 0 1359 1359 port = int(args[2]) 1360 if len(args) > 3:1360 if (len(args) > 3): 1361 1361 passwd = args[3] 1362 1362 else: … … 1368 1368 1369 1369 def closeportalCmd(ctx, args): 1370 if len(args) < 2:1371 print ("usage: closeportal name")1370 if (len(args) < 2): 1371 print "usage: closeportal name" 1372 1372 return 0 1373 1373 mach = argsToMach(ctx, args) … … 1379 1379 1380 1380 def 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>" 1383 1383 return 0 1384 1384 mach = argsToMach(ctx, args) … … 1392 1392 cpu = args[1] 1393 1393 if plug: 1394 print ("Adding CPU %d..." % (cpu))1394 print "Adding CPU %d..." % (cpu) 1395 1395 mach.hotPlugCPU(cpu) 1396 1396 else: 1397 print ("Removing CPU %d..." % (cpu))1397 print "Removing CPU %d..." % (cpu) 1398 1398 mach.hotUnplugCPU(cpu) 1399 1399 1400 1400 def 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" 1403 1403 return 0 1404 1404 mach = argsToMach(ctx, args) … … 1413 1413 1414 1414 def 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" 1417 1417 return 0 1418 1418 mach = argsToMach(ctx, args) … … 1428 1428 def setvar(_ctx, _mach, args): 1429 1429 expr = 'mach.'+args[0]+' = '+args[1] 1430 print ("Executing", expr)1431 exec (expr)1430 print "Executing", expr 1431 exec expr 1432 1432 1433 1433 def 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" 1436 1436 return 0 1437 1437 mach = argsToMach(ctx, args) … … 1444 1444 key = args[0] 1445 1445 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) 1447 1447 mach.setExtraData(key, value) 1448 1448 1449 1449 def 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>" 1452 1452 return 0 1453 1453 key = args[2] … … 1467 1467 1468 1468 def printExtraKey(obj, key, value): 1469 print ("%s: '%s' = '%s'" % (obj, key, value))1469 print "%s: '%s' = '%s'" % (obj, key, value) 1470 1470 1471 1471 def 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>" 1474 1474 return 0 1475 1475 if len(args) == 3: … … 1498 1498 1499 1499 def aliasCmd(ctx, args): 1500 if len(args) == 3:1500 if (len(args) == 3): 1501 1501 aliases[args[1]] = args[2] 1502 1502 return 0 1503 1503 1504 for (key, value) in list(aliases.items()):1505 print ("'%s' is an alias for '%s'" % (key, value))1504 for (key, value) in aliases.items(): 1505 print "'%s' is an alias for '%s'" % (key, value) 1506 1506 return 0 1507 1507 1508 1508 def verboseCmd(ctx, args): 1509 1509 global g_fVerbose 1510 if len(args) > 1:1510 if (len(args) > 1): 1511 1511 g_fVerbose = (args[1]=='on') 1512 1512 else: … … 1516 1516 def colorsCmd(ctx, args): 1517 1517 global g_fHasColors 1518 if len(args) > 1:1518 if (len(args) > 1): 1519 1519 g_fHasColors = (args[1] == 'on') 1520 1520 else: … … 1525 1525 vbox = ctx['vb'] 1526 1526 try: 1527 print ("VirtualBox version %s" % (colored(vbox.version, 'blue')))1528 except Exception ase:1527 print "VirtualBox version %s" % (colored(vbox.version, 'blue')) 1528 except Exception, e: 1529 1529 printErr(ctx, e) 1530 1530 if g_fVerbose: 1531 1531 traceback.print_exc() 1532 1532 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:" 1536 1536 #for ud in ctx['global'].getArray(vbox, 'sharedFolders'): 1537 1537 # printSf(ctx, sf) 1538 1538 host = vbox.host 1539 1539 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) 1542 1542 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) 1549 1549 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:") 1555 1555 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:") 1559 1559 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:") 1563 1563 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:") 1567 1567 for ud in ctx['global'].getArray(host, 'USBDevices'): 1568 1568 printHostUsbDev(ctx, ud) … … 1570 1570 if ctx['perf']: 1571 1571 for metric in ctx['perf'].query(["*"], [host]): 1572 print (metric['name'], metric['values_as_string'])1572 print metric['name'], metric['values_as_string'] 1573 1573 1574 1574 return 0 1575 1575 1576 1576 def 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)" 1579 1579 return 0 1580 1580 mach = argsToMach(ctx, args) … … 1589 1589 1590 1590 def 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)" 1593 1593 return 0 1594 1594 mach = argsToMach(ctx, args) … … 1603 1603 1604 1604 def 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)" 1607 1607 return 0 1608 1608 mach = argsToMach(ctx, args) … … 1617 1617 1618 1618 def 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)" 1621 1621 return 0 1622 1622 mach = argsToMach(ctx, args) … … 1631 1631 1632 1632 def monitorVBoxCmd(ctx, args): 1633 if len(args) > 2:1634 print ("usage: monitorVBox (duration)")1633 if (len(args) > 2): 1634 print "usage: monitorVBox (duration)" 1635 1635 return 0 1636 1636 dur = 5 … … 1659 1659 1660 1660 def 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>" 1663 1663 return 0 1664 1664 mach = argsToMach(ctx, args) … … 1690 1690 1691 1691 def 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>" 1694 1694 return 0 1695 1695 mach = argsToMach(ctx, args) … … 1698 1698 1699 1699 log = 0 1700 if len(args) > 2:1700 if (len(args) > 2): 1701 1701 log = args[2] 1702 1702 … … 1704 1704 while True: 1705 1705 data = mach.readLog(log, uOffset, 4096) 1706 if len(data) == 0:1706 if (len(data) == 0): 1707 1707 break 1708 1708 # print adds either NL or space to chunks not ending with a NL … … 1713 1713 1714 1714 def 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>" 1717 1717 return 0 1718 1718 mach = argsToMach(ctx, args) … … 1721 1721 1722 1722 log = 0 1723 if len(args) > 3:1723 if (len(args) > 3): 1724 1724 log = args[3] 1725 1725 … … 1729 1729 # to reduce line splits on buffer boundary 1730 1730 data = mach.readLog(log, uOffset, 512*1024) 1731 if len(data) == 0:1731 if (len(data) == 0): 1732 1732 break 1733 1733 d = str(data).split("\n") … … 1737 1737 for mt in match: 1738 1738 s = s.replace(mt, colored(mt, 'red')) 1739 print (s)1739 print s 1740 1740 uOffset += len(data) 1741 1741 … … 1744 1744 1745 1745 def 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>" 1748 1748 return 0 1749 1749 mach = argsToMach(ctx, args) … … 1752 1752 1753 1753 log = 0 1754 if len(args) > 2:1754 if (len(args) > 2): 1755 1755 log = args[2] 1756 1756 … … 1762 1762 # to reduce line splits on buffer boundary 1763 1763 data = mach.readLog(log, uOffset, 512*1024) 1764 if len(data) == 0:1764 if (len(data) == 0): 1765 1765 break 1766 1766 d = str(data).split("\n") 1767 1767 for s in d: 1768 1768 if active: 1769 print (s)1769 print s 1770 1770 if context == 0: 1771 1771 active = False … … 1777 1777 active = True 1778 1778 context = 50 1779 print (s)1779 print s 1780 1780 uOffset += len(data) 1781 1781 … … 1785 1785 expr = ' '.join(args[1:]) 1786 1786 try: 1787 exec (expr)1788 except Exception ase:1787 exec expr 1788 except Exception, e: 1789 1789 printErr(ctx, e) 1790 1790 if g_fVerbose: … … 1799 1799 1800 1800 def runScriptCmd(ctx, args): 1801 if len(args) != 2:1802 print ("usage: runScript <script>")1801 if (len(args) != 2): 1802 print "usage: runScript <script>" 1803 1803 return 0 1804 1804 try: 1805 1805 lf = open(args[1], 'r') 1806 except IOError ase:1807 print ("cannot open:", args[1], ":", e)1806 except IOError, e: 1807 print "cannot open:", args[1], ":", e 1808 1808 return 0 1809 1809 … … 1819 1819 break 1820 1820 1821 except Exception ase:1821 except Exception, e: 1822 1822 printErr(ctx, e) 1823 1823 if g_fVerbose: … … 1827 1827 1828 1828 def sleepCmd(ctx, args): 1829 if len(args) != 2:1830 print ("usage: sleep <secs>")1829 if (len(args) != 2): 1830 print "usage: sleep <secs>" 1831 1831 return 0 1832 1832 … … 1840 1840 1841 1841 def shellCmd(ctx, args): 1842 if len(args) < 2:1843 print ("usage: shell <commands>")1842 if (len(args) < 2): 1843 print "usage: shell <commands>" 1844 1844 return 0 1845 1845 cmd = ' '.join(args[1:]) … … 1854 1854 1855 1855 def 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>" 1858 1858 return 0 1859 1859 1860 1860 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): 1865 1865 url = args[1] 1866 1866 else: 1867 1867 url = None 1868 1868 1869 if len(args) > 2:1869 if (len(args) > 2): 1870 1870 user = args[2] 1871 1871 else: 1872 1872 user = "" 1873 1873 1874 if len(args) > 3:1874 if (len(args) > 3): 1875 1875 passwd = args[3] 1876 1876 else: … … 1881 1881 ctx['vb'] = vbox 1882 1882 try: 1883 print ("Running VirtualBox version %s" % (vbox.version))1884 except Exception ase:1883 print "Running VirtualBox version %s" % (vbox.version) 1884 except Exception, e: 1885 1885 printErr(ctx, e) 1886 1886 if g_fVerbose: … … 1890 1890 1891 1891 def disconnectCmd(ctx, args): 1892 if len(args) != 1:1893 print ("usage: disconnect")1892 if (len(args) != 1): 1893 print "usage: disconnect" 1894 1894 return 0 1895 1895 1896 1896 if ctx['vb'] is None: 1897 print ("Not connected yet.")1897 print "Not connected yet." 1898 1898 return 0 1899 1899 … … 1909 1909 def reconnectCmd(ctx, args): 1910 1910 if ctx['wsinfo'] is None: 1911 print ("Never connected...")1911 print "Never connected..." 1912 1912 return 0 1913 1913 … … 1920 1920 ctx['vb'] = ctx['global'].platform.connect(url, user, passwd) 1921 1921 try: 1922 print ("Running VirtualBox version %s" % (ctx['vb'].version))1923 except Exception ase:1922 print "Running VirtualBox version %s" % (ctx['vb'].version) 1923 except Exception, e: 1924 1924 printErr(ctx, e) 1925 1925 if g_fVerbose: … … 1929 1929 def exportVMCmd(ctx, args): 1930 1930 if len(args) < 3: 1931 print ("usage: exportVm <machine> <path> <format> <license>")1931 print "usage: exportVm <machine> <path> <format> <license>" 1932 1932 return 0 1933 1933 mach = argsToMach(ctx, args) … … 1935 1935 return 0 1936 1936 path = args[2] 1937 if len(args) > 3:1937 if (len(args) > 3): 1938 1938 fmt = args[3] 1939 1939 else: 1940 1940 fmt = "ovf-1.0" 1941 if len(args) > 4:1941 if (len(args) > 4): 1942 1942 lic = args[4] 1943 1943 else: … … 1949 1949 progress = app.write(fmt, path) 1950 1950 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) 1952 1952 else: 1953 1953 reportError(ctx, progress) … … 2053 2053 extCode = extScancodes.get(ch, []) 2054 2054 if len(extCode) == 0: 2055 print ("bad ext", ch)2055 print "bad ext", ch 2056 2056 return extCode 2057 2057 … … 2125 2125 def typeGuestCmd(ctx, args): 2126 2126 if len(args) < 3: 2127 print ("usage: typeGuest <machine> <text> <charDelay>")2127 print "usage: typeGuest <machine> <text> <charDelay>" 2128 2128 return 0 2129 2129 mach = argsToMach(ctx, args) … … 2161 2161 verbose = False 2162 2162 hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks') 2163 print (colCat(ctx, "Hard disks:"))2163 print colCat(ctx, "Hard disks:") 2164 2164 for hdd in hdds: 2165 2165 if hdd.state != ctx['global'].constants.MediumState_Created: 2166 2166 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))) 2168 2168 2169 2169 dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages') 2170 print (colCat(ctx, "CD/DVD disks:"))2170 print colCat(ctx, "CD/DVD disks:") 2171 2171 for dvd in dvds: 2172 2172 if dvd.state != ctx['global'].constants.MediumState_Created: 2173 2173 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))) 2175 2175 2176 2176 floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages') 2177 print (colCat(ctx, "Floppy disks:"))2177 print colCat(ctx, "Floppy disks:") 2178 2178 for floppy in floppys: 2179 2179 if floppy.state != ctx['global'].constants.MediumState_Created: 2180 2180 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))) 2182 2182 2183 2183 return 0 2184 2184 2185 2185 def listUsbCmd(ctx, args): 2186 if len(args) > 1:2187 print ("usage: listUsb")2186 if (len(args) > 1): 2187 print "usage: listUsb" 2188 2188 return 0 2189 2189 … … 2202 2202 2203 2203 def 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" 2206 2206 return 0 2207 2207 … … 2216 2216 progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, )) 2217 2217 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) 2221 2221 reportError(ctx,progress) 2222 2222 return 0 … … 2225 2225 2226 2226 def registerHddCmd(ctx, args): 2227 if len(args) < 2:2228 print ("usage: registerHdd location")2227 if (len(args) < 2): 2228 print "usage: registerHdd location" 2229 2229 return 0 2230 2230 … … 2236 2236 parentId = "" 2237 2237 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) 2239 2239 return 0 2240 2240 … … 2244 2244 2245 2245 def 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" 2248 2248 return 0 2249 2249 … … 2256 2256 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False) 2257 2257 except: 2258 print ("no HDD with path %s registered" % (loc))2258 print "no HDD with path %s registered" % (loc) 2259 2259 return 0 2260 2260 if len(args) > 3: … … 2279 2279 2280 2280 def 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" 2283 2283 return 0 2284 2284 … … 2291 2291 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False) 2292 2292 except: 2293 print ("no HDD with path %s registered" % (loc))2293 print "no HDD with path %s registered" % (loc) 2294 2294 return 0 2295 2295 … … 2298 2298 2299 2299 def 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>" 2302 2302 return 0 2303 2303 2304 2304 vbox = ctx['vb'] 2305 2305 loc = args[1] 2306 if len(args) > 2:2306 if (len(args) > 2): 2307 2307 vmunreg = int(args[2]) 2308 2308 else: … … 2311 2311 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False) 2312 2312 except: 2313 print ("no HDD with path %s registered" % (loc))2313 print "no HDD with path %s registered" % (loc) 2314 2314 return 0 2315 2315 … … 2318 2318 try: 2319 2319 for mach in machs: 2320 print ("Trying to detach from %s" % (mach))2320 print "Trying to detach from %s" % (mach) 2321 2321 detachMedium(ctx, mach, hdd) 2322 except Exception ase:2323 print ('failed: ', e)2322 except Exception, e: 2323 print 'failed: ', e 2324 2324 return 0 2325 2325 hdd.close() … … 2327 2327 2328 2328 def removeHddCmd(ctx, args): 2329 if len(args) != 2:2330 print ("usage: removeHdd path")2329 if (len(args) != 2): 2330 print "usage: removeHdd path" 2331 2331 return 0 2332 2332 … … 2336 2336 hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, False) 2337 2337 except: 2338 print ("no HDD with path %s registered" % (loc))2338 print "no HDD with path %s registered" % (loc) 2339 2339 return 0 2340 2340 … … 2345 2345 2346 2346 def registerIsoCmd(ctx, args): 2347 if len(args) < 2:2348 print ("usage: registerIso location")2347 if (len(args) < 2): 2348 print "usage: registerIso location" 2349 2349 return 0 2350 2350 … … 2352 2352 loc = args[1] 2353 2353 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) 2355 2355 return 0 2356 2356 2357 2357 def unregisterIsoCmd(ctx, args): 2358 if len(args) != 2:2359 print ("usage: unregisterIso path")2358 if (len(args) != 2): 2359 print "usage: unregisterIso path" 2360 2360 return 0 2361 2361 … … 2365 2365 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False) 2366 2366 except: 2367 print ("no DVD with path %s registered" % (loc))2367 print "no DVD with path %s registered" % (loc) 2368 2368 return 0 2369 2369 2370 2370 progress = dvd.close() 2371 print ("Unregistered ISO at %s" % (colPath(ctx, loc)))2371 print "Unregistered ISO at %s" % (colPath(ctx, loc)) 2372 2372 2373 2373 return 0 2374 2374 2375 2375 def removeIsoCmd(ctx, args): 2376 if len(args) != 2:2377 print ("usage: removeIso path")2376 if (len(args) != 2): 2377 print "usage: removeIso path" 2378 2378 return 0 2379 2379 … … 2383 2383 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False) 2384 2384 except: 2385 print ("no DVD with path %s registered" % (loc))2385 print "no DVD with path %s registered" % (loc) 2386 2386 return 0 2387 2387 2388 2388 progress = dvd.deleteStorage() 2389 2389 if progressBar(ctx, progress): 2390 print ("Removed ISO at %s" % (colPath(ctx, dvd.location)))2390 print "Removed ISO at %s" % (colPath(ctx, dvd.location)) 2391 2391 else: 2392 2392 reportError(ctx, progress) … … 2394 2394 2395 2395 def 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" 2398 2398 return 0 2399 2399 … … 2406 2406 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False) 2407 2407 except: 2408 print ("no DVD with path %s registered" % (loc))2408 print "no DVD with path %s registered" % (loc) 2409 2409 return 0 2410 2410 if len(args) > 3: … … 2417 2417 2418 2418 def 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" 2421 2421 return 0 2422 2422 … … 2429 2429 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False) 2430 2430 except: 2431 print ("no DVD with path %s registered" % (loc))2431 print "no DVD with path %s registered" % (loc) 2432 2432 return 0 2433 2433 … … 2436 2436 2437 2437 def 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" 2440 2440 return 0 2441 2441 … … 2448 2448 dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, False) 2449 2449 except: 2450 print ("no DVD with path %s registered" % (loc))2450 print "no DVD with path %s registered" % (loc) 2451 2451 return 0 2452 2452 … … 2463 2463 2464 2464 def 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" 2467 2467 return 0 2468 2468 … … 2490 2490 2491 2491 def 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>" 2494 2494 return 0 2495 2495 … … 2497 2497 ctrltype = enumFromString(ctx, 'StorageControllerType', args[4]) 2498 2498 if ctrltype == None: 2499 print ("Controller type %s unknown" % (args[4]))2499 print "Controller type %s unknown" % (args[4]) 2500 2500 return 0 2501 2501 else: … … 2507 2507 bus = enumFromString(ctx, 'StorageBus', args[3]) 2508 2508 if bus is None: 2509 print ("Bus type %s unknown" % (args[3]))2509 print "Bus type %s unknown" % (args[3]) 2510 2510 return 0 2511 2511 name = args[2] … … 2514 2514 2515 2515 def 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" 2518 2518 return 0 2519 2519 … … 2526 2526 2527 2527 def usbctr(ctx, mach, console, args): 2528 if args[0]:2528 if (args[0]): 2529 2529 console.attachUSBDevice(args[1], "") 2530 2530 else: … … 2532 2532 2533 2533 def 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" 2536 2536 return 0 2537 2537 … … 2544 2544 2545 2545 def 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" 2548 2548 return 0 2549 2549 … … 2557 2557 2558 2558 def guiCmd(ctx, args): 2559 if len(args) > 1:2560 print ("usage: gui")2559 if (len(args) > 1): 2560 print "usage: gui" 2561 2561 return 0 2562 2562 … … 2572 2572 2573 2573 def 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>" 2576 2576 return 0 2577 2577 … … 2596 2596 2597 2597 def 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" 2600 2600 return 0 2601 2601 … … 2617 2617 def snapshotCmd(ctx, args): 2618 2618 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" 2622 2622 return 0 2623 2623 … … 2627 2627 cmd = args[2] 2628 2628 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>" 2631 2631 return 0 2632 2632 name = args[3] 2633 if len(args) > 4:2633 if (len(args) > 4): 2634 2634 desc = args[4] 2635 2635 else: … … 2639 2639 2640 2640 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" 2643 2643 return 0 2644 2644 name = args[3] … … 2648 2648 2649 2649 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" 2652 2652 return 0 2653 2653 snap = mach.currentSnapshot() … … 2656 2656 2657 2657 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" 2660 2660 return 0 2661 2661 name = args[3] … … 2664 2664 return 0 2665 2665 2666 print ("Command '%s' is unknown" % (cmd))2666 print "Command '%s' is unknown" % (cmd) 2667 2667 return 0 2668 2668 … … 2683 2683 first = 0 2684 2684 msg = '' 2685 for aliasmode, aliaskey in list(alias.items()):2685 for aliasmode, aliaskey in alias.iteritems(): 2686 2686 if first == 0: 2687 2687 first = 1 … … 2689 2689 msg += ', ' 2690 2690 if int(nat.aliasMode) & aliaskey: 2691 msg += '% s: %s' % (aliasmode, 'on')2691 msg += '%d: %s' % (aliasmode, 'on') 2692 2692 else: 2693 msg += '%s: %s' % (aliasmode, 'off') 2693 msg += '%d: %s' % (aliasmode, 'off') 2694 msg += ')' 2694 2695 return (0, [msg]) 2695 2696 else: … … 2697 2698 if 'default' not in args: 2698 2699 for a in range(1, len(args)): 2699 if args[a] not in alias:2700 print ('Invalid alias mode: ' + args[a])2701 print (natAlias.__doc__)2700 if not alias.has_key(args[a]): 2701 print 'Invalid alias mode: ' + args[a] 2702 print natAlias.__doc__ 2702 2703 return (1, None) 2703 2704 nat.aliasMode = int(nat.aliasMode) | alias[args[a]] … … 2722 2723 else: 2723 2724 if args[1] < 16000: 2724 print ('invalid mtu value (%s not in range [65 - 16000])' % (args[1]))2725 print 'invalid mtu value (%s not in range [65 - 16000])' % (args[1]) 2725 2726 return (1, None) 2726 2727 for i in range(2, len(args)): 2727 2728 if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024: 2728 print ('invalid %s parameter (%i not in range [8-1024])' % (i, args[i]))2729 print 'invalid %s parameter (%i not in range [8-1024])' % (i, args[i]) 2729 2730 return (1, None) 2730 2731 a = [args[1]] … … 2734 2735 else: 2735 2736 for i in range(2, len(args)): a.append(args[i]) 2736 #print (a)2737 #print a 2737 2738 nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4])) 2738 2739 return (0, None) … … 2785 2786 cmd = args[1] 2786 2787 if len(args) != 3: 2787 print ('invalid args:', args)2788 print (natTftp.__doc__)2788 print 'invalid args:', args 2789 print natTftp.__doc__ 2789 2790 return (1, None) 2790 2791 if cmd == 'prefix': nat.TFTPPrefix = args[2] … … 2792 2793 elif cmd == 'server': nat.TFTPNextServer = args[2] 2793 2794 else: 2794 print ("invalid cmd:", cmd)2795 print "invalid cmd:", cmd 2795 2796 return (1, None) 2796 2797 return (0, None) … … 2817 2818 pfcmd = { 2818 2819 'simple': { 2819 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 5,2820 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5, 2820 2821 'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4])) 2821 2822 }, 2822 2823 'no_name': { 2823 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 7,2824 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7, 2824 2825 'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6])) 2825 2826 }, 2826 2827 'ex': { 2827 'validate': lambda: args[1] in list(pfcmd.keys()) and args[2] in list(proto.keys()) and len(args) == 8,2828 'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8, 2828 2829 'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7])) 2829 2830 }, … … 2835 2836 2836 2837 if not pfcmd[args[1]]['validate'](): 2837 print ('invalid port-forwarding or args of sub command ', args[1])2838 print (natPortForwarding.__doc__)2838 print 'invalid port-forwarding or args of sub command ', args[1] 2839 print natPortForwarding.__doc__ 2839 2840 return (1, None) 2840 2841 … … 2855 2856 (addr, mask) = args[1].split('/') 2856 2857 if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32: 2857 print ('Invalid arguments')2858 print 'Invalid arguments' 2858 2859 return (1, None) 2859 2860 nat.network = args[1] … … 2879 2880 if len(args) < 2 or args[1] == 'help': 2880 2881 if len(args) > 2: 2881 print (natcommands[args[2]].__doc__)2882 print natcommands[args[2]].__doc__ 2882 2883 else: 2883 print (natCmd.__doc__)2884 print natCmd.__doc__ 2884 2885 return 0 2885 2886 if len(args) == 1 or len(args) < 4 or args[3] not in natcommands: 2886 print (natCmd.__doc__)2887 print natCmd.__doc__ 2887 2888 return 0 2888 2889 mach = ctx['argsToMach'](args) 2889 2890 if mach == None: 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)))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)) 2894 2895 return 0 2895 2896 nicnum = int(args[2]) … … 2918 2919 for r in report: 2919 2920 msg ='%s nic%d %s: %s' % (mach.name, nicnum, func, r) 2920 print (msg)2921 print msg 2921 2922 return 0 2922 2923 … … 2929 2930 yesno = {'off' : 0, 'on' : 1} 2930 2931 if args[1] not in yesno: 2931 print ('%s isn\'t acceptable, please choose %s' % (args[1], list(yesno.keys())))2932 print '%s isn\'t acceptable, please choose %s' % (args[1], yesno.keys()) 2932 2933 return (1, None) 2933 2934 adapter.__setattr__(attr, yesno[args[1]]) … … 2952 2953 else: 2953 2954 if not args[1].isdigit(): 2954 print ('%s isn\'t a number' % (args[1]))2955 return(1, None)2955 print '%s isn\'t a number' % (args[1]) 2956 print (1, None) 2956 2957 adapter.lineSpeed = int(args[1]) 2957 2958 return (0, None) … … 2975 2976 if len(args) == 1: 2976 2977 nictypes = ctx['const'].all_values('NetworkAdapterType') 2977 for key in list(nictypes.keys()):2978 for key in nictypes.keys(): 2978 2979 if str(adapter.adapterType) == str(nictypes[key]): 2979 2980 return (0, str(key)) … … 2981 2982 else: 2982 2983 nictypes = ctx['const'].all_values('NetworkAdapterType') 2983 if args[1] not in list(nictypes.keys()):2984 print ('%s not in acceptable values (%s)' % (args[1], list(nictypes.keys())))2984 if args[1] not in nictypes.keys(): 2985 print '%s not in acceptable values (%s)' % (args[1], nictypes.keys()) 2985 2986 return (1, None) 2986 2987 adapter.adapterType = nictypes[args[1]] … … 3001 3002 ctx['global'].constants.NetworkAttachmentType_Generic: ('Generic', ''), 3002 3003 } 3003 if type(adapter.attachmentType) != int: 3004 import types 3005 if type(adapter.attachmentType) != types.IntType: 3004 3006 t = str(adapter.attachmentType) 3005 3007 else: … … 3035 3037 'f': lambda: ctx['global'].constants.NetworkAttachmentType_Generic} 3036 3038 } 3037 if args[1] not in list(nicAttachmentType.keys()):3038 print ('%s not in acceptable values (%s)' % (args[1], list(nicAttachmentType.keys())))3039 if args[1] not in nicAttachmentType.keys(): 3040 print '%s not in acceptable values (%s)' % (args[1], nicAttachmentType.keys()) 3039 3041 return (1, None) 3040 3042 if not nicAttachmentType[args[1]]['v'](): 3041 print (nicAttachmentType.__doc__)3043 print nicAttachmentType.__doc__ 3042 3044 return (1, None) 3043 3045 nicAttachmentType[args[1]]['p']() … … 3065 3067 if len(args) == 3 \ 3066 3068 and args[2] in niccomand: 3067 print (niccomand[args[2]].__doc__)3069 print niccomand[args[2]].__doc__ 3068 3070 else: 3069 print (nicCmd.__doc__)3071 print nicCmd.__doc__ 3070 3072 return 0 3071 3073 3072 3074 vm = ctx['argsToMach'](args) 3073 3075 if vm is None: 3074 print ('please specify vm')3076 print 'please specify vm' 3075 3077 return 0 3076 3078 3077 3079 if len(args) < 3 \ 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)))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)) 3080 3082 return 0 3081 3083 nicnum = int(args[2]) … … 3090 3092 vm.saveSettings() 3091 3093 if report is not None: 3092 print ('%s nic %d %s: %s' % (vm.name, nicnum, args[3], report))3094 print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report) 3093 3095 session.unlockMachine() 3094 3096 return 0 … … 3097 3099 def promptCmd(ctx, args): 3098 3100 if len(args) < 2: 3099 print ("Current prompt: '%s'" % (ctx['prompt']))3101 print "Current prompt: '%s'" % (ctx['prompt']) 3100 3102 return 0 3101 3103 … … 3105 3107 def foreachCmd(ctx, args): 3106 3108 if len(args) < 3: 3107 print ("usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']")3109 print "usage: foreach scope command, where scope is XPath-like expression //vms/vm[@CPUCount='2']" 3108 3110 return 0 3109 3111 … … 3115 3117 e.apply(cmd) 3116 3118 except: 3117 print ("Error executing")3119 print "Error executing" 3118 3120 traceback.print_exc() 3119 3121 return 0 … … 3121 3123 def foreachvmCmd(ctx, args): 3122 3124 if len(args) < 2: 3123 print ("foreachvm command <args>")3125 print "foreachvm command <args>" 3124 3126 return 0 3125 3127 cmdargs = args[1:] … … 3131 3133 3132 3134 def recordDemoCmd(ctx, args): 3133 if len(args) < 3:3134 print ("usage: recordDemo vm filename (duration)")3135 if (len(args) < 3): 3136 print "usage: recordDemo vm filename (duration)" 3135 3137 return 0 3136 3138 mach = argsToMach(ctx, args) … … 3145 3147 3146 3148 def playbackDemoCmd(ctx, args): 3147 if len(args) < 3:3148 print ("usage: playbackDemo vm filename (duration)")3149 if (len(args) < 3): 3150 print "usage: playbackDemo vm filename (duration)" 3149 3151 return 0 3150 3152 mach = argsToMach(ctx, args) … … 3167 3169 for a in assigned: 3168 3170 if a.isPhysicalDevice: 3169 print ("%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)))3171 print "%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress)) 3170 3172 3171 3173 atts = ctx['global'].getArray(console, 'attachedPCIDevices') 3172 3174 for a in atts: 3173 3175 if a.isPhysicalDevice: 3174 print ("%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)))3176 print "%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress)) 3175 3177 else: 3176 print ("%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress)))3178 print "%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress)) 3177 3179 return 3178 3180 … … 3186 3188 3187 3189 def lspciCmd(ctx, args): 3188 if len(args) < 2:3189 print ("usage: lspci vm")3190 if (len(args) < 2): 3191 print "usage: lspci vm" 3190 3192 return 0 3191 3193 mach = argsToMach(ctx, args) … … 3196 3198 3197 3199 def attachpciCmd(ctx, args): 3198 if len(args) < 3:3199 print ("usage: attachpci vm hostpci <guestpci>")3200 if (len(args) < 3): 3201 print "usage: attachpci vm hostpci <guestpci>" 3200 3202 return 0 3201 3203 mach = argsToMach(ctx, args) … … 3204 3206 hostaddr = parsePci(args[2]) 3205 3207 if hostaddr == -1: 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: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): 3210 3212 guestaddr = parsePci(args[3]) 3211 3213 if guestaddr == -1: 3212 print ("invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3]))3214 print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3]) 3213 3215 return 0 3214 3216 else: … … 3218 3220 3219 3221 def detachpciCmd(ctx, args): 3220 if len(args) < 3:3221 print ("usage: detachpci vm hostpci")3222 if (len(args) < 3): 3223 print "usage: detachpci vm hostpci" 3222 3224 return 0 3223 3225 mach = argsToMach(ctx, args) … … 3226 3228 hostaddr = parsePci(args[2]) 3227 3229 if hostaddr == -1: 3228 print ("invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]))3230 print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2]) 3229 3231 return 0 3230 3232 … … 3233 3235 3234 3236 def gotoCmd(ctx, args): 3235 if len(args) < 2:3236 print ("usage: goto line")3237 if (len(args) < 2): 3238 print "usage: goto line" 3237 3239 return 0 3238 3240 … … 3271 3273 'verbose':['Toggle verbosity', verboseCmd, 0], 3272 3274 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0], 3273 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print (m.name, "has", m.memorySize, "M")\'', evalCmd, 0],3275 'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name, "has", m.memorySize, "M"\'', evalCmd, 0], 3274 3276 'quit':['Exits', quitCmd, 0], 3275 3277 'host':['Show host information', hostCmd, 0], … … 3327 3329 'prompt' : ['Control shell prompt', promptCmd, 0], 3328 3330 'foreachvm' : ['Perform command for each VM', foreachvmCmd, 0], 3329 'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print (obj.name)"', foreachCmd, 0],3331 'foreach' : ['Generic "for each" construction, using XPath-like notation: foreach //vms/vm[@OSTypeId=\'MacOS\'] "print obj.name"', foreachCmd, 0], 3330 3332 'recordDemo':['Record demo: recordDemo Win32 file.dmo 10', recordDemoCmd, 0], 3331 3333 'playbackDemo':['Playback demo: playbackDemo Win32 file.dmo 10', playbackDemoCmd, 0], … … 3342 3344 ci = commands.get(c, None) 3343 3345 if ci == None: 3344 print ("Unknown command: '%s', type 'help' for list of known commands" % (c))3346 print "Unknown command: '%s', type 'help' for list of known commands" % (c) 3345 3347 return 0 3346 3348 if ctx['remote'] and ctx['vb'] is None: 3347 3349 if c not in ['connect', 'reconnect', 'help', 'quit']: 3348 print ("First connect to remote server with %s command." % (colored('connect', 'blue')))3350 print "First connect to remote server with %s command." % (colored('connect', 'blue')) 3349 3351 return 0 3350 3352 return ci[1](ctx, args) … … 3352 3354 3353 3355 def runCommand(ctx, cmd): 3354 if not cmd: return 03356 if len(cmd) == 0: return 0 3355 3357 args = split_no_quotes(cmd) 3356 3358 if len(args) == 0: return 0 … … 3362 3364 # 3363 3365 # def runTestCmd(ctx, args): 3364 # print ("Testy test", ctx['vb'])3366 # print "Testy test", ctx['vb'] 3365 3367 # return 0 3366 3368 # … … 3379 3381 d = {} 3380 3382 try: 3381 exec (compile(open(filename).read(), filename, 'exec'), d, d)3382 for (k, v) in list(d['commands'].items()):3383 execfile(filename, d, d) 3384 for (k, v) in d['commands'].items(): 3383 3385 if g_fVerbose: 3384 print ("customize: adding \"%s\" - %s" % (k, v[0]))3386 print "customize: adding \"%s\" - %s" % (k, v[0]) 3385 3387 cmds[k] = [v[0], v[1], filename] 3386 3388 except: 3387 print ("Error loading user extensions from %s" % (filename))3389 print "Error loading user extensions from %s" % (filename) 3388 3390 traceback.print_exc() 3389 3391 … … 3421 3423 if vbox is not None: 3422 3424 try: 3423 print ("Running VirtualBox version %s" % (vbox.version))3424 except Exception ase:3425 print "Running VirtualBox version %s" % (vbox.version) 3426 except Exception, e: 3425 3427 printErr(ctx, e) 3426 3428 if g_fVerbose: … … 3459 3461 cmd = 'runScript %s'% (g_sScriptFile) 3460 3462 elif g_sCmd is not None: 3461 cmd = next(it)3463 cmd = it.next() 3462 3464 else: 3463 if sys.version_info[0] <= 2: 3464 cmd = raw_input(ctx['prompt']) 3465 else: 3466 cmd = input(ctx['prompt']) 3465 cmd = raw_input(ctx['prompt']) 3467 3466 done = runCommand(ctx, cmd) 3468 3467 if done != 0: break … … 3470 3469 break 3471 3470 except KeyboardInterrupt: 3472 print ('====== You can type quit or q to leave')3471 print '====== You can type quit or q to leave' 3473 3472 except StopIteration: 3474 3473 break 3475 3474 except EOFError: 3476 3475 break 3477 except Exception ase:3476 except Exception, e: 3478 3477 printErr(ctx, e) 3479 3478 if g_fVerbose: … … 3537 3536 3538 3537 if options.autopath: 3539 asLocations = [ os.getcwd(), ] 3540 try: sScriptDir = os.path.dirname(os.path.abspath(__file__)) 3538 asLocations = [ os.getcwd(), ]; 3539 try: sScriptDir = os.path.dirname(os.path.abspath(__file__)); 3541 3540 except: pass; # In case __file__ isn't there. 3542 3541 else: 3543 3542 if platform.system() in [ 'SunOS', ]: 3544 asLocations.append(os.path.join(sScriptDir, 'amd64')) 3545 asLocations.append(sScriptDir) 3543 asLocations.append(os.path.join(sScriptDir, 'amd64')); 3544 asLocations.append(sScriptDir); 3546 3545 3547 3546 … … 3551 3550 if os.path.isfile(os.path.join(sCurLoc, "VirtualBox")) \ 3552 3551 or os.path.isfile(os.path.join(sCurLoc, "VirtualBox.exe")): 3553 print ("Autodetected VBOX_PROGRAM_PATH as", sCurLoc)3552 print "Autodetected VBOX_PROGRAM_PATH as", sCurLoc 3554 3553 os.environ["VBOX_PROGRAM_PATH"] = sCurLoc 3555 3554 sPath = sCurLoc 3556 break 3555 break; 3557 3556 if sPath: 3558 3557 sys.path.append(os.path.join(sPath, "sdk", "installer")) … … 3562 3561 for sCurLoc in asLocations: 3563 3562 if os.path.isfile(os.path.join(sCurLoc, "sdk", "bindings", "VirtualBox.xidl")): 3564 sCurLoc = os.path.join(sCurLoc, "sdk") 3565 print ("Autodetected VBOX_SDK_PATH as", sCurLoc)3563 sCurLoc = os.path.join(sCurLoc, "sdk"); 3564 print "Autodetected VBOX_SDK_PATH as", sCurLoc 3566 3565 os.environ["VBOX_SDK_PATH"] = sCurLoc 3567 sPath = sCurLoc 3568 break 3566 sPath = sCurLoc; 3567 break; 3569 3568 if sPath: 3570 sTmp = os.path.join(sCurLoc, ' bindings', 'xpcom', 'python')3569 sTmp = os.path.join(sCurLoc, 'sdk', 'bindings', 'xpcom', 'python'); 3571 3570 if os.path.isdir(sTmp): 3572 sys.path.append(sTmp) 3573 del sTmp 3574 del sPath, asLocations 3571 sys.path.append(sTmp); 3572 del sTmp; 3573 del sPath, asLocations; 3575 3574 3576 3575 -
trunk/src/VBox/Installer/common/vboxapisetup.py
r59769 r59795 1 1 """ 2 Copyright (C) 2009-201 6Oracle Corporation2 Copyright (C) 2009-2015 Oracle Corporation 3 3 4 4 This file is part of VirtualBox Open Source Edition (OSE), as … … 19 19 comCache1 = os.path.join(get_python_lib(), 'win32com', 'gen_py') 20 20 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 22 22 shutil.rmtree(comCache1, True) 23 23 shutil.rmtree(comCache2, True) -
trunk/src/VBox/Main/glue/vboxapi.py
r59769 r59795 7 7 __copyright__ = \ 8 8 """ 9 Copyright (C) 2009-201 6Oracle Corporation9 Copyright (C) 2009-2015 Oracle Corporation 10 10 11 11 This file is part of VirtualBox Open Source Edition (OSE), as … … 32 32 xrange = range 33 33 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) 34 92 35 93 # … … 167 225 # Try case-insensitivity workaround for class attributes (COM methods). 168 226 sAttrLower = sAttr.lower() 169 for k in list(self.__class__.__dict__.keys()):227 for k in self.__class__.__dict__.keys(): 170 228 if k.lower() == sAttrLower: 171 229 setattr(self.__class__, sAttr, self.__class__.__dict__[k]) -
trunk/src/VBox/Main/webservice/websrv-python.xsl
r59769 r59795 193 193 if self.isarray: 194 194 return self.handle.__next() 195 raise TypeError ("iteration over non-sequence")195 raise TypeError, "iteration over non-sequence" 196 196 197 197 def __size(self): 198 198 if self.isarray: 199 199 return self.handle.__size() 200 raise TypeError ("iteration over non-sequence")200 raise TypeError, "iteration over non-sequence" 201 201 202 202 def __len__(self): 203 203 if self.isarray: 204 204 return self.handle.__len__() 205 raise TypeError ("iteration over non-sequence")205 raise TypeError, "iteration over non-sequence" 206 206 207 207 def __getitem__(self, index): 208 208 if self.isarray: 209 209 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" 211 211 212 212 def __str__(self): … … 326 326 327 327 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' 329 329 </xsl:for-each> 330 330 … … 332 332 if self.isarray: 333 333 return self.handle.__next() 334 raise TypeError ("iteration over non-sequence")334 raise TypeError, "iteration over non-sequence" 335 335 336 336 def __size(self): 337 337 if self.isarray: 338 338 return self.handle.__size() 339 raise TypeError ("iteration over non-sequence")339 raise TypeError, "iteration over non-sequence" 340 340 341 341 def __len__(self): 342 342 if self.isarray: 343 343 return self.handle.__len__() 344 raise TypeError ("iteration over non-sequence")344 raise TypeError, "iteration over non-sequence" 345 345 346 346 def __getitem__(self, index): 347 347 if self.isarray: 348 348 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" 350 350 <xsl:call-template name="xsltprocNewlineOutputHack"/> 351 351 </xsl:template> … … 511 511 c = self.map.get(handle,-1) 512 512 if c == -1: 513 raise Error ('wrong refcount')513 raise Error, 'wrong refcount' 514 514 c = c - 1 515 515 if c == 0: … … 533 533 if self.isarray: 534 534 return self.handle.__next() 535 raise TypeError ("iteration over non-sequence")535 raise TypeError, "iteration over non-sequence" 536 536 537 537 def __size(self): 538 538 if self.isarray: 539 539 return self.handle.__size() 540 raise TypeError ("iteration over non-sequence")540 raise TypeError, "iteration over non-sequence" 541 541 542 542 def __len__(self): 543 543 if self.isarray: 544 544 return self.handle.__len__() 545 raise TypeError ("iteration over non-sequence")545 raise TypeError, "iteration over non-sequence" 546 546 547 547 def __getitem__(self, index): 548 548 if self.isarray: 549 549 return String(self.mgr, self.handle[index]) 550 raise TypeError ("iteration over non-sequence")550 raise TypeError, "iteration over non-sequence" 551 551 552 552 def __str__(self): … … 624 624 if self.isarray: 625 625 return self.handle.__next() 626 raise TypeError ("iteration over non-sequence")626 raise TypeError, "iteration over non-sequence" 627 627 628 628 def __size(self): 629 629 if self.isarray: 630 630 return self.handle.__size() 631 raise TypeError ("iteration over non-sequence")631 raise TypeError, "iteration over non-sequence" 632 632 633 633 def __len__(self): 634 634 if self.isarray: 635 635 return self.handle.__len__() 636 raise TypeError ("iteration over non-sequence")636 raise TypeError, "iteration over non-sequence" 637 637 638 638 def __getitem__(self, index): 639 639 if self.isarray: 640 640 return Boolean(self.mgr, self.handle[index]) 641 raise TypeError ("iteration over non-sequence")641 raise TypeError, "iteration over non-sequence" 642 642 643 643 class Number: … … 650 650 if self.isarray: 651 651 return self.handle.__next() 652 raise TypeError ("iteration over non-sequence")652 raise TypeError, "iteration over non-sequence" 653 653 654 654 def __size(self): 655 655 if self.isarray: 656 656 return self.handle.__size() 657 raise TypeError ("iteration over non-sequence")657 raise TypeError, "iteration over non-sequence" 658 658 659 659 def __len__(self): 660 660 if self.isarray: 661 661 return self.handle.__len__() 662 raise TypeError ("iteration over non-sequence")662 raise TypeError, "iteration over non-sequence" 663 663 664 664 def __str__(self): … … 711 711 self.handle = mgr.decodebase64(handle) 712 712 else: 713 raise TypeError ("only octet arrays")713 raise TypeError, "only octet arrays" 714 714 715 715 def __getitem__(self, index): … … 731 731 if self.isarray: 732 732 return UnsignedInt(self.mgr, self.handle[index]) 733 raise TypeError ("iteration over non-sequence")733 raise TypeError, "iteration over non-sequence" 734 734 735 735 … … 743 743 if self.isarray: 744 744 return Int(self.mgr, self.handle[index]) 745 raise TypeError ("iteration over non-sequence")745 raise TypeError, "iteration over non-sequence" 746 746 747 747 class UnsignedShort(Number): … … 754 754 if self.isarray: 755 755 return UnsignedShort(self.mgr, self.handle[index]) 756 raise TypeError ("iteration over non-sequence")756 raise TypeError, "iteration over non-sequence" 757 757 758 758 class Short(Number): … … 765 765 if self.isarray: 766 766 return Short(self.mgr, self.handle[index]) 767 raise TypeError ("iteration over non-sequence")767 raise TypeError, "iteration over non-sequence" 768 768 769 769 class UnsignedLong(Number): … … 776 776 if self.isarray: 777 777 return UnsignedLong(self.mgr, self.handle[index]) 778 raise TypeError ("iteration over non-sequence")778 raise TypeError, "iteration over non-sequence" 779 779 780 780 class Long(Number): … … 787 787 if self.isarray: 788 788 return Long(self.mgr, self.handle[index]) 789 raise TypeError ("iteration over non-sequence")789 raise TypeError, "iteration over non-sequence" 790 790 791 791 class Double(Number): … … 798 798 if self.isarray: 799 799 return Double(self.mgr, self.handle[index]) 800 raise TypeError ("iteration over non-sequence")800 raise TypeError, "iteration over non-sequence" 801 801 802 802 class Float(Number): … … 809 809 if self.isarray: 810 810 return Float(self.mgr, self.handle[index]) 811 raise TypeError ("iteration over non-sequence")811 raise TypeError, "iteration over non-sequence" 812 812 813 813 class IUnknown: … … 826 826 if self.isarray: 827 827 return self.handle.__next() 828 raise TypeError ("iteration over non-sequence")828 raise TypeError, "iteration over non-sequence" 829 829 830 830 def __size(self): 831 831 if self.isarray: 832 832 return self.handle.__size() 833 raise TypeError ("iteration over non-sequence")833 raise TypeError, "iteration over non-sequence" 834 834 835 835 def __len__(self): 836 836 if self.isarray: 837 837 return self.handle.__len__() 838 raise TypeError ("iteration over non-sequence")838 raise TypeError, "iteration over non-sequence" 839 839 840 840 def __getitem__(self, index): 841 841 if self.isarray: 842 842 return IUnknown(self.mgr, self.handle[index]) 843 raise TypeError ("iteration over non-sequence")843 raise TypeError, "iteration over non-sequence" 844 844 845 845 def __str__(self): -
trunk/src/VBox/ValidationKit/testdriver/vbox.py
r59777 r59795 9 9 __copyright__ = \ 10 10 """ 11 Copyright (C) 2010-201 6Oracle Corporation11 Copyright (C) 2010-2015 Oracle Corporation 12 12 13 13 This file is part of VirtualBox Open Source Edition (OSE), as -
trunk/src/libs/xpcom18a4/python/Makefile.kmk
r59769 r59795 5 5 6 6 # 7 # Copyright (C) 2009-201 6Oracle Corporation7 # Copyright (C) 2009-2015 Oracle Corporation 8 8 # 9 9 # This file is part of VirtualBox Open Source Edition (OSE), as … … 27 27 # 28 28 # List of supported Python versions, defining a number of 29 # VBOX_PYTHON[26|27|31|32|33|34|35|DEF]_[INC|LIB] variables 30 # which get picked up below. 29 # VBOX_PYTHON[25|26|27|DEF]_[INC|LIB] variables which get picked up below. 31 30 # 32 31 ifeq ($(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 33 37 if !defined(VBOX_WITHOUT_VBOXPYTHON_FOR_OSX_10_6) \ 34 38 && ( !defined(VBOX_OSE) \ … … 45 49 VBOX_PYTHON27_LIB_X86 = $(VBOX_PYTHON27_LIB) 46 50 endif 47 # No Python 3.x yet as part of OSX versions including El Capitan, 10.11.48 51 49 52 else … … 112 115 113 116 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 114 176 ifdef VBOX_PYTHON26_INC 115 177 # … … 151 213 VBoxPython2_7_x86_INCS = $(VBOX_PYTHON27_INC) 152 214 VBoxPython2_7_x86_LIBS = $(VBOX_PYTHON27_LIB_X86) 153 endif154 endif155 156 ifdef VBOX_PYTHON31_INC157 #158 # Python 3.1 version159 #160 DLLS += VBoxPython3_1161 VBoxPython3_1_EXTENDS = VBoxPythonBase162 VBoxPython3_1_EXTENDS_BY = appending163 VBoxPython3_1_TEMPLATE = XPCOM164 VBoxPython3_1_INCS = $(VBOX_PYTHON31_INC)165 VBoxPython3_1_LIBS = $(VBOX_PYTHON31_LIB)166 167 ifdef VBOX_WITH_32_ON_64_MAIN_API168 DLLS += VBoxPython3_1_x86169 VBoxPython3_1_x86_EXTENDS = VBoxPythonBase_x86170 VBoxPython3_1_x86_EXTENDS_BY = appending171 VBoxPython3_1_x86_TEMPLATE = XPCOM172 VBoxPython3_1_x86_INCS = $(VBOX_PYTHON31_INC)173 VBoxPython3_1_x86_LIBS = $(VBOX_PYTHON31_LIB_X86)174 endif175 endif176 177 ifdef VBOX_PYTHON32_INC178 #179 # Python 3.2 version180 #181 DLLS += VBoxPython3_2182 VBoxPython3_2_EXTENDS = VBoxPythonBase183 VBoxPython3_2_EXTENDS_BY = appending184 VBoxPython3_2_TEMPLATE = XPCOM185 VBoxPython3_2_INCS = $(VBOX_PYTHON32_INC)186 VBoxPython3_2_LIBS = $(VBOX_PYTHON32_LIB)187 188 ifdef VBOX_WITH_32_ON_64_MAIN_API189 DLLS += VBoxPython3_2_x86190 VBoxPython3_2_x86_EXTENDS = VBoxPythonBase_x86191 VBoxPython3_2_x86_EXTENDS_BY = appending192 VBoxPython3_2_x86_TEMPLATE = XPCOM193 VBoxPython3_2_x86_INCS = $(VBOX_PYTHON32_INC)194 VBoxPython3_2_x86_LIBS = $(VBOX_PYTHON32_LIB_X86)195 endif196 endif197 198 ifdef VBOX_PYTHON33_INC199 #200 # Python 3.3 version201 #202 DLLS += VBoxPython3_3203 VBoxPython3_3_EXTENDS = VBoxPythonBase204 VBoxPython3_3_EXTENDS_BY = appending205 VBoxPython3_3_TEMPLATE = XPCOM206 VBoxPython3_3_INCS = $(VBOX_PYTHON33_INC)207 VBoxPython3_3_LIBS = $(VBOX_PYTHON33_LIB)208 209 ifdef VBOX_WITH_32_ON_64_MAIN_API210 DLLS += VBoxPython3_3_x86211 VBoxPython3_3_x86_EXTENDS = VBoxPythonBase_x86212 VBoxPython3_3_x86_EXTENDS_BY = appending213 VBoxPython3_3_x86_TEMPLATE = XPCOM214 VBoxPython3_3_x86_INCS = $(VBOX_PYTHON33_INC)215 VBoxPython3_3_x86_LIBS = $(VBOX_PYTHON33_LIB_X86)216 endif217 endif218 219 ifdef VBOX_PYTHON34_INC220 #221 # Python 3.4 version222 #223 DLLS += VBoxPython3_4224 VBoxPython3_4_EXTENDS = VBoxPythonBase225 VBoxPython3_4_EXTENDS_BY = appending226 VBoxPython3_4_TEMPLATE = XPCOM227 VBoxPython3_4_INCS = $(VBOX_PYTHON34_INC)228 VBoxPython3_4_LIBS = $(VBOX_PYTHON34_LIB)229 230 ifdef VBOX_WITH_32_ON_64_MAIN_API231 DLLS += VBoxPython3_4_x86232 VBoxPython3_4_x86_EXTENDS = VBoxPythonBase_x86233 VBoxPython3_4_x86_EXTENDS_BY = appending234 VBoxPython3_4_x86_TEMPLATE = XPCOM235 VBoxPython3_4_x86_INCS = $(VBOX_PYTHON34_INC)236 VBoxPython3_4_x86_LIBS = $(VBOX_PYTHON34_LIB_X86)237 endif238 endif239 240 ifdef VBOX_PYTHON35_INC241 #242 # Python 3.5 version243 #244 DLLS += VBoxPython3_5245 VBoxPython3_5_EXTENDS = VBoxPythonBase246 VBoxPython3_5_EXTENDS_BY = appending247 VBoxPython3_5_TEMPLATE = XPCOM248 VBoxPython3_5_INCS = $(VBOX_PYTHON35_INC)249 VBoxPython3_5_LIBS = $(VBOX_PYTHON35_LIB)250 251 ifdef VBOX_WITH_32_ON_64_MAIN_API252 DLLS += VBoxPython3_5_x86253 VBoxPython3_5_x86_EXTENDS = VBoxPythonBase_x86254 VBoxPython3_5_x86_EXTENDS_BY = appending255 VBoxPython3_5_x86_TEMPLATE = XPCOM256 VBoxPython3_5_x86_INCS = $(VBOX_PYTHON35_INC)257 VBoxPython3_5_x86_LIBS = $(VBOX_PYTHON35_LIB_X86)258 215 endif 259 216 endif -
trunk/src/libs/xpcom18a4/python/__init__.py
r59769 r59795 38 38 39 39 # The XPCOM (Cross Platform COM) package. 40 from __future__ import print_function 41 import sys 42 if sys.version_info[0] <= 2: 43 import exceptions 44 XPCOMBaseException = exceptions.Exception 45 else: 46 XPCOMBaseException = Exception 40 import exceptions 47 41 48 42 # A global "verbose" flag - currently used by the … … 54 48 # The standard XPCOM exception object. 55 49 # Instances of this class are raised by the XPCOM extension module. 56 class Exception( XPCOMBaseException):50 class Exception(exceptions.Exception): 57 51 def __init__(self, errno, message = None): 58 52 assert int(errno) == errno, "The errno param must be an integer" 59 53 self.errno = errno 60 54 self.msg = message 61 XPCOMBaseException.__init__(self, errno)55 exceptions.Exception.__init__(self, errno) 62 56 def __str__(self): 63 57 if not hr_map: 64 from .import nsError65 for name, val in list(nsError.__dict__.items()):58 import nsError 59 for name, val in nsError.__dict__.items(): 66 60 if type(val)==type(0): 67 61 hr_map[val] = name … … 86 80 def __init__(self, errno=None, *args, **kw): 87 81 if errno is None: 88 from .import nsError82 import nsError 89 83 errno = nsError.NS_ERROR_FAILURE 90 84 Exception.__init__(self, errno, *args, **kw) … … 104 98 pass 105 99 def write(self, msg): 106 import xpcom._xpcom as_xpcom100 import _xpcom 107 101 _xpcom.LogConsoleMessage(msg) 108 102 def close(self): … … 110 104 111 105 def setupLogging(): 112 import os 113 if sys.version_info[0] <= 2: 114 import threading, thread 106 import sys, os, threading, thread 115 107 hdlr = logging.StreamHandler(ConsoleServiceStream()) 116 108 fmt = logging.Formatter(logging.BASIC_FORMAT) … … 121 113 # Later versions of logging use an RLock, so we detect an "old" style 122 114 # handler and update its lock 123 if sys.version_info[0] <= 2: 124 if type(hdlr.lock) == thread.LockType: 125 hdlr.lock = threading.RLock() 115 if type(hdlr.lock) == thread.LockType: 116 hdlr.lock = threading.RLock() 126 117 127 118 logger.addHandler(hdlr) … … 135 126 # open without buffering so never pending output 136 127 stream = open(filename, "wU", 0) 137 except IOError as why: 138 print("pyxpcom failed to open log file '%s': %s" % (filename, why), file=sys.stderr) 128 except IOError, why: 129 print >> sys.stderr, "pyxpcom failed to open log file '%s': %s" \ 130 % (filename, why) 139 131 # stream remains default 140 132 141 133 hdlr = logging.StreamHandler(stream) 142 134 # see above - fix a deadlock problem on this handler too. 143 if sys.version_info[0] <= 2: 144 if type(hdlr.lock) == thread.LockType: 145 hdlr.lock = threading.RLock() 135 if type(hdlr.lock) == thread.LockType: 136 hdlr.lock = threading.RLock() 146 137 147 138 fmt = logging.Formatter(logging.BASIC_FORMAT) -
trunk/src/libs/xpcom18a4/python/client/__init__.py
r59769 r59795 37 37 38 38 import os 39 from types import MethodType 39 import new 40 40 import logging 41 41 from xpcom import xpt, COMException, nsError, logger … … 126 126 # Exec the code object 127 127 tempNameSpace = {} 128 exec (codeObject, globals(), tempNameSpace)128 exec codeObject in globals(), tempNameSpace 129 129 ret = tempNameSpace[name] 130 if iid not in interface_method_cache:130 if not interface_method_cache.has_key(iid): 131 131 interface_method_cache[iid] = {} 132 132 interface_method_cache[iid][name] = ret … … 153 153 if flags & FLAGS_TO_IGNORE == 0: 154 154 if flags & XPT_MD_SETTER: 155 param_flags = list([(x.param_flags,) + xpt.MakeReprForInvoke(x) for x in m.params])155 param_flags = map(lambda x: (x.param_flags,) + xpt.MakeReprForInvoke(x), m.params) 156 156 setters[m.name] = m.method_index, param_flags 157 157 elif flags & XPT_MD_GETTER: 158 param_flags = list([(x.param_flags,) + xpt.MakeReprForInvoke(x) for x in m.params])158 param_flags = map(lambda x: (x.param_flags,) + xpt.MakeReprForInvoke(x), m.params) 159 159 getters[m.name] = m.method_index, param_flags 160 160 else: … … 220 220 except COMException: 221 221 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" 223 223 224 224 def __int__(self): … … 281 281 for nominated_iid in interface_infos: 282 282 # Interface may appear twice in the class info list, so check this here. 283 if no minated_iid not in self.__dict__['_interface_infos_']:283 if not self.__dict__['_interface_infos_'].has_key(nominated_iid): 284 284 # Just invoke our QI on the object 285 285 self.queryInterface(nominated_iid) … … 290 290 contractid_info_cache[real_cid] = contractid_info 291 291 else: 292 for key, val in list(contractid_info.items()):292 for key, val in contractid_info.items(): 293 293 self.__dict__[key].update(val) 294 294 … … 300 300 # rebuild the world for each new object. 301 301 iis = self.__dict__['_interface_infos_'] 302 assert iid not in iis, "Already remembered this interface!"302 assert not iis.has_key(iid), "Already remembered this interface!" 303 303 try: 304 304 method_infos, getters, setters, constants = BuildInterfaceInfo(iid) 305 except COMException aswhy:305 except COMException, why: 306 306 # Failing to build an interface info generally isn't a real 307 307 # problem - its probably just that the interface is non-scriptable. … … 314 314 iis[iid] = method_infos, getters, setters, constants 315 315 names = self.__dict__['_name_to_interface_iid_'] 316 for name in list(method_infos.keys()): names[name] = iid317 for name in list(getters.keys()): names[name] = iid318 for name in list(setters.keys()): names[name] = iid319 for name in list(constants.keys()): names[name] = iid316 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 320 320 321 321 def QueryInterface(self, iid): 322 if iid in self._interfaces_:323 assert iid_name in self._interface_names_, "_interfaces_ has the key, but _interface_names_ does not!"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!" 324 324 return self 325 325 # Haven't seen this before - do a real QI. 326 if iid not in self._interface_infos_:326 if not self._interface_infos_.has_key(iid): 327 327 self._remember_interface_info(iid) 328 328 iface_info = self._interface_infos_[iid] … … 350 350 def __getattr__(self, attr): 351 351 if attr in _special_getattr_names: 352 raise AttributeError (attr)352 raise AttributeError, attr 353 353 # First allow the interface name to return the "raw" interface 354 354 interface = self.__dict__['_interface_names_'].get(attr, None) … … 375 375 # Some interfaces may provide this name via "native" support. 376 376 # Loop over all interfaces, and if found, cache it for next time. 377 for interface in list(self.__dict__['_interfaces_'].values()):377 for interface in self.__dict__['_interfaces_'].values(): 378 378 try: 379 379 ret = getattr(interface, attr) … … 382 382 except AttributeError: 383 383 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) 385 385 386 386 def __setattr__(self, attr, val): … … 397 397 setattr(interface, attr, val) 398 398 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) 400 400 401 401 def _get_classinfo_repr_(self): … … 410 410 self.__dict__['_tried_classinfo_'] = 0 411 411 412 iface_names = list(self.__dict__['_interface_names_'].keys())412 iface_names = self.__dict__['_interface_names_'].keys() 413 413 try: 414 414 iface_names.remove("nsISupports") … … 436 436 self.__dict__.update(constants) 437 437 # We remember the constant names to prevent the user trying to assign to them! 438 self.__dict__['_constant_names_'] = list(constants.keys())438 self.__dict__['_constant_names_'] = constants.keys() 439 439 440 440 def __getattr__(self, attr): 441 441 # Allow the underlying interface to provide a better implementation if desired. 442 442 if attr in _special_getattr_names: 443 raise AttributeError (attr)443 raise AttributeError, attr 444 444 445 445 ret = getattr(self.__dict__['_comobj_'], attr, None) … … 449 449 unbound_method = self.__dict__['_methods_'].get(attr, None) 450 450 if unbound_method is not None: 451 return MethodType(unbound_method, self)451 return new.instancemethod(unbound_method, self, self.__class__) 452 452 453 453 getters = self.__dict__['_property_getters_'] … … 456 456 method_index, param_infos = info 457 457 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!" 459 459 args = ( param_infos, () ) 460 460 return XPTC_InvokeByIndex(self._comobj_, method_index, args) … … 467 467 # Cache it locally 468 468 self.__dict__['_methods_'][attr] = unbound_method 469 return MethodType(unbound_method, self)470 471 raise AttributeError ("XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr))469 return new.instancemethod(unbound_method, self, self.__class__) 470 471 raise AttributeError, "XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr) 472 472 473 473 def __setattr__(self, attr, val): 474 474 # If we already have a __dict__ item of that name, and its not one of 475 475 # our constants, we just directly set it, and leave. 476 if attr in self.__dict__and attr not in self.__dict__['_constant_names_']:476 if self.__dict__.has_key(attr) and attr not in self.__dict__['_constant_names_']: 477 477 self.__dict__[attr] = val 478 478 return … … 481 481 info = setters.get(attr) 482 482 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) 484 484 method_index, param_infos = info 485 485 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!" 487 487 real_param_infos = ( param_infos, (val,) ) 488 488 return XPTC_InvokeByIndex(self._comobj_, method_index, real_param_infos) … … 527 527 try: 528 528 return Component(self._comobj_.QueryReferent(iid)._comobj_, iid) 529 except COMException asdetails:529 except COMException, details: 530 530 if details.errno != nsError.NS_ERROR_NULL_POINTER: 531 531 raise -
trunk/src/libs/xpcom18a4/python/components.py
r59769 r59795 37 37 38 38 # This module provides the JavaScript "components" interface 39 from . import xpt 40 import xpcom 41 import xpcom._xpcom as _xpcom 39 import xpt 40 import xpcom, _xpcom 42 41 import xpcom.client 43 42 import xpcom.server 44 45 StringTypes = [bytes, str] 43 import types 44 45 StringTypes = [types.StringType, types.UnicodeType] 46 46 47 47 def _get_good_iid(iid): … … 79 79 if self._dict_data is None: 80 80 self._dict_data = self._build_dict() 81 return list(self._dict_data.keys())81 return self._dict_data.keys() 82 82 def items(self): 83 83 if self._dict_data is None: 84 84 self._dict_data = self._build_dict() 85 return list(self._dict_data.items())85 return self._dict_data.items() 86 86 def values(self): 87 87 if self._dict_data is None: 88 88 self._dict_data = self._build_dict() 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)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) 94 94 95 95 def __len__(self): … … 99 99 100 100 def __getattr__(self, attr): 101 if self._dict_data is not None and attr in self._dict_data:101 if self._dict_data is not None and self._dict_data.has_key(attr): 102 102 return self._dict_data[attr] 103 103 return self._get_one(attr) 104 104 def __getitem__(self, item): 105 if self._dict_data is not None and item in self._dict_data:105 if self._dict_data is not None and self._dict_data.has_key(item): 106 106 return self._dict_data[item] 107 107 return self._get_one(item) … … 120 120 other_iid = getattr(other, "_iidobj_", other) 121 121 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_iid126 122 def __hash__(self): 127 123 return hash(self._iidobj_) … … 129 125 return str(self._iidobj_) 130 126 def __getitem__(self, item): 131 raise TypeError ("components.interface objects are not subscriptable")127 raise TypeError, "components.interface objects are not subscriptable" 132 128 def __setitem__(self, item, value): 133 raise TypeError ("components.interface objects are not subscriptable")129 raise TypeError, "components.interface objects are not subscriptable" 134 130 def __setattr__(self, attr, value): 135 raise AttributeError ("Can not set attributes on components.Interface objects")131 raise AttributeError, "Can not set attributes on components.Interface objects" 136 132 def __getattr__(self, attr): 137 133 # Support constants as attributes. … … 143 139 c[c_ob.name] = c_ob.value 144 140 _constants_by_iid_map[self._iidobj_] = c 145 if attr in c:141 if c.has_key(attr): 146 142 return c[attr] 147 raise AttributeError ("'%s' interfaces do not define a constant '%s'" % (self.name, attr))143 raise AttributeError, "'%s' interfaces do not define a constant '%s'" % (self.name, attr) 148 144 149 145 … … 152 148 try: 153 149 item = interfaceInfoManager.GetInfoForName(name) 154 except xpcom.COMException aswhy:150 except xpcom.COMException, why: 155 151 # Present a better exception message, and give a more useful error code. 156 from .import nsError152 import nsError 157 153 raise xpcom.COMException(nsError.NS_ERROR_NO_INTERFACE, "The interface '%s' does not exist" % (name,)) 158 154 return _Interface(item.GetName(), item.GetIID()) … … 184 180 self.clsid = rc 185 181 return rc 186 raise AttributeError ("%s class has no attribute '%s'" % (self.contractid, attr))182 raise AttributeError, "%s class has no attribute '%s'" % (self.contractid, attr) 187 183 def createInstance(self, iid = None): 188 184 import xpcom.client 189 185 try: 190 186 return xpcom.client.Component(self.contractid, _get_good_iid(iid)) 191 except xpcom.COMException asdetails:192 from .import nsError187 except xpcom.COMException, details: 188 import nsError 193 189 # Handle "no such component" in a cleaner way for the user. 194 190 if details.errno == nsError.NS_ERROR_FACTORY_NOT_REGISTERED: … … 223 219 224 220 # The ID function 225 ID = _xpcom.I D221 ID = _xpcom.IID 226 222 227 223 # A helper to cleanup our namespace as xpcom shuts down. -
trunk/src/libs/xpcom18a4/python/file.py
r59769 r59795 156 156 self.close() 157 157 if mode != "r": 158 raise ValueError ("only 'r' mode supported")158 raise ValueError, "only 'r' mode supported'" 159 159 io_service = components.classes["@mozilla.org/network/io-service;1"] \ 160 160 .getService(components.interfaces.nsIIOService) … … 165 165 # Mozilla asserts and starts saying "NULL POINTER" if this is wrong! 166 166 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)" 168 168 % (url_ob.spec,)) 169 169 self.channel = io_service.newChannelFromURI(url_ob) … … 202 202 self.inputStream.init(self.fileIO) 203 203 else: 204 raise ValueError ("Unknown mode")204 raise ValueError, "Unknown mode" 205 205 206 206 def close(self): … … 226 226 got = got + file.read() 227 227 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)) 229 229 230 230 def _DoTestBufferRead(file, expected): … … 240 240 got = got + str(buffer[:num]) 241 241 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)) 243 243 244 244 def _TestLocalFile(): … … 266 266 # Open the same file again for writing - this should delete the old one. 267 267 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,) 269 269 test_file = LocalFile(fname, "w") 270 270 test_file.write(data) … … 305 305 def _TestURI(url): 306 306 test_file = URIFile(url) 307 print ("Opened file is", test_file)307 print "Opened file is", test_file 308 308 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) 310 310 test_file.close() 311 311 … … 313 313 import sys 314 314 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" 316 316 _TestAll() 317 317 else: -
trunk/src/libs/xpcom18a4/python/gen_python_deps.py
r59772 r59795 2 2 3 3 """ 4 Copyright (C) 2009-201 6Oracle Corporation4 Copyright (C) 2009-2013 Oracle Corporation 5 5 6 6 This file is part of VirtualBox Open Source Edition (OSE), as … … 14 14 15 15 import os,sys 16 from distutils.version import StrictVersion17 16 18 versions = ["2. 6", "2.7", "3.1", "3.2", "3.3", "3.4", "3.5"]17 versions = ["2.3", "2.4", "2.5", "2.6", "2.7",] 19 18 prefixes = ["/usr", "/usr/local", "/opt", "/opt/local"] 20 19 known = {} … … 42 41 43 42 def print_vars(vers, known, sep, bitness_magic): 44 print ("VBOX_PYTHON%s_INC=%s%s" %(vers, known[0], sep))43 print "VBOX_PYTHON%s_INC=%s%s" %(vers, known[0], sep) 45 44 if bitness_magic > 0: 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))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) 48 47 else: 49 print ("VBOX_PYTHON%s_LIB=%s%s" %(vers, known[1], sep))48 print "VBOX_PYTHON%s_LIB=%s%s" %(vers, known[1], sep) 50 49 51 50 … … 92 91 93 92 for v in versions: 94 if StrictVersion(v) < StrictVersion('2.6'):95 continue96 93 for p in prefixes: 97 94 c = checkPair(p, v, dllpre, dllsuff, bitness_magic) … … 99 96 known[v] = c 100 97 break 101 keys = list(known.keys())98 keys = known.keys() 102 99 # we want default to be the lowest versioned Python 103 100 keys.sort() -
trunk/src/libs/xpcom18a4/python/primitives.py
r59769 r59795 35 35 better = _primitives_map[prin.type] 36 36 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,) 38 38 prin = prin.QueryInterface(better) 39 39 return prin.data -
trunk/src/libs/xpcom18a4/python/server/__init__.py
r59777 r59795 38 38 # The xpcom.server package. 39 39 40 from xpcom.server.policy import DefaultPolicy40 from policy import DefaultPolicy 41 41 from xpcom import _xpcom 42 42 … … 80 80 # Python! 81 81 def NS_GetModule( serviceManager, nsIFile ): 82 from .import loader82 import loader 83 83 iid = _xpcom.IID_nsIModule 84 84 return WrapObject(loader.MakePythonComponentLoaderModule(serviceManager, nsIFile), iid, bWrapClient = 0) 85 85 86 86 def _shutdown(): 87 from server.policy import _shutdown87 from policy import _shutdown 88 88 _shutdown() -
trunk/src/libs/xpcom18a4/python/server/loader.py
r59769 r59795 38 38 import xpcom 39 39 from xpcom import components, logger 40 from . import module 41 import glob 42 import os 40 41 import module 42 43 import glob, os, types 44 43 45 from xpcom.client import Component 44 46 … … 55 57 # For now, just run over all classes looking for likely candidates. 56 58 comps = [] 57 for name, object in list(py_module.__dict__.items()):59 for name, object in py_module.__dict__.items(): 58 60 try: 59 if (type(object) == type or issubclass(object, object)) and \61 if (type(object) == types.ClassType or issubclass(object, object)) and \ 60 62 _has_good_attr(object, "_com_interfaces_") and \ 61 63 _has_good_attr(object, "_reg_clsid_") and \ … … 146 148 self.autoRegisterComponent(when, entry) 147 149 # Handle some common user errors 148 except xpcom.COMException asdetails:150 except xpcom.COMException, details: 149 151 from xpcom import nsError 150 152 # If the interface name does not exist, suppress the traceback … … 154 156 else: 155 157 logger.exception("Registration of '%s' failed!", entry.leafName) 156 except SyntaxError asdetails:158 except SyntaxError, details: 157 159 # Syntax error in source file - no useful traceback here either. 158 160 logger.error("Registration of '%s' failed\n %s", … … 224 226 225 227 def MakePythonComponentLoaderModule(serviceManager, nsIFile): 226 from .import module228 import module 227 229 return module.Module( [PythonComponentLoader] ) -
trunk/src/libs/xpcom18a4/python/server/module.py
r59769 r59795 39 39 from xpcom import nsError 40 40 41 from .import factory41 import factory 42 42 43 43 import types … … 66 66 # void function. 67 67 fname = os.path.basename(location.path) 68 for klass in list(self.components.values()):68 for klass in self.components.values(): 69 69 reg_contractid = klass._reg_contractid_ 70 print ("Registering '%s' (%s)" % (reg_contractid, fname))70 print "Registering '%s' (%s)" % (reg_contractid, fname) 71 71 reg_desc = getattr(klass, "_reg_desc_", reg_contractid) 72 72 compMgr = compMgr.queryInterface(components.interfaces.nsIComponentRegistrar) … … 85 85 def unregisterSelf(self, compMgr, location, loaderStr): 86 86 # void function. 87 for klass in list(self.components.values()):87 for klass in self.components.values(): 88 88 ok = 1 89 89 try: … … 99 99 ok = 0 100 100 if ok: 101 print ("Successfully unregistered", klass.__name__)101 print "Successfully unregistered", klass.__name__ 102 102 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)" 104 104 105 105 def canUnload(self, compMgr): -
trunk/src/libs/xpcom18a4/python/server/policy.py
r59769 r59795 43 43 import types 44 44 import logging 45 import sys46 45 47 46 … … 62 61 _supports_primitives_map_ = {} # Filled on first use. 63 62 64 _interface_sequence_types_ = tuple, list 65 if sys.version_info[0] <= 2: 66 _string_types_ = str, unicode 67 else: 68 _string_types_ = bytes, str 63 _interface_sequence_types_ = types.TupleType, types.ListType 64 _string_types_ = types.StringType, types.UnicodeType 69 65 XPTI_GetInterfaceInfoManager = _xpcom.XPTI_GetInterfaceInfoManager 70 66 … … 146 142 self._iid_ = iid 147 143 if ni is None: 148 raise ValueError ("The object '%r' can not be used as a COM object" % (instance,))144 raise ValueError, "The object '%r' can not be used as a COM object" % (instance,) 149 145 # This is really only a check for the user 150 146 if __debug__: … … 290 286 if logger.isEnabledFor(logging.DEBUG): 291 287 try: 292 raise exc_info[0] (exc_info[1]).with_traceback(exc_info[2])288 raise exc_info[0], exc_info[1], exc_info[2] 293 289 except: 294 290 logger.debug("'%s' raised COM Exception %s", … … 298 294 # As above, trick the logging module to handle Python 2.3 299 295 try: 300 raise exc_info[0] (exc_info[1]).with_traceback(exc_info[2])296 raise exc_info[0], exc_info[1], exc_info[2] 301 297 except: 302 298 logger.exception("Unhandled exception calling '%s'", func_name) … … 335 331 _supports_primitives_data_ = [ 336 332 ("nsISupportsCString", "__str__", str), 337 ("nsISupportsString", "__unicode__", str),338 ("nsISupportsPRUint64", "__long__", int),339 ("nsISupportsPRInt64", "__long__", int),333 ("nsISupportsString", "__unicode__", unicode), 334 ("nsISupportsPRUint64", "__long__", long), 335 ("nsISupportsPRInt64", "__long__", long), 340 336 ("nsISupportsPRUint32", "__int__", int), 341 337 ("nsISupportsPRInt32", "__int__", int), -
trunk/src/libs/xpcom18a4/python/src/ErrorUtils.cpp
r59769 r59795 111 111 c += "('%s', "; 112 112 // Pull a trick to ensure a valid string - use Python repr! 113 #if PY_MAJOR_VERSION <= 2114 113 PyObject *obMessage = PyString_FromString(pszMessageText); 115 #else116 PyObject *obMessage = PyUnicode_FromString(pszMessageText);117 #endif118 114 if (obMessage) { 119 115 PyObject *repr = PyObject_Repr(obMessage); 120 116 if (repr) { 121 #if PY_MAJOR_VERSION <= 2122 117 c += PyString_AsString(repr); 123 #else124 c += PyUnicode_AsUTF8(repr);125 #endif126 118 Py_DECREF(repr); 127 119 } … … 201 193 PyObject *temp = PyObject_Str(exc_typ); 202 194 if (temp) { 203 #if PY_MAJOR_VERSION <= 2204 195 streamout += PyString_AsString(temp); 205 #else206 streamout += PyUnicode_AsUTF8(temp);207 #endif208 196 Py_DECREF(temp); 209 197 } else … … 213 201 temp = PyObject_Str(exc_val); 214 202 if (temp) { 215 #if PY_MAJOR_VERSION <= 2216 203 streamout += PyString_AsString(temp); 217 #else218 streamout += PyUnicode_AsUTF8(temp);219 #endif220 204 Py_DECREF(temp); 221 205 } else … … 371 355 PyObject *obResult = NULL; 372 356 373 #if PY_MAJOR_VERSION <= 2374 357 /* Import the modules we need - cStringIO and traceback */ 375 358 modStringIO = PyImport_ImportModule("cStringIO"); … … 387 370 if (obStringIO==NULL) 388 371 TRACEBACK_FETCH_ERROR("cStringIO.StringIO() failed\n"); 389 #else390 /* Import the modules we need - io and traceback */391 modStringIO = PyImport_ImportModule("io");392 if (modStringIO==NULL)393 TRACEBACK_FETCH_ERROR("cant import io\n");394 395 modTB = PyImport_ImportModule("traceback");396 if (modTB==NULL)397 TRACEBACK_FETCH_ERROR("cant import traceback\n");398 /* Construct a StringIO object */399 obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO");400 if (obFuncStringIO==NULL)401 TRACEBACK_FETCH_ERROR("cant find io.StringIO\n");402 obStringIO = PyObject_CallObject(obFuncStringIO, NULL);403 if (obStringIO==NULL)404 TRACEBACK_FETCH_ERROR("io.StringIO() failed\n");405 #endif406 372 /* Get the traceback.print_exception function, and call it. */ 407 373 obFuncTB = PyObject_GetAttrString(modTB, "print_tb"); … … 430 396 431 397 /* And it should be a string all ready to go - duplicate it. */ 432 #if PY_MAJOR_VERSION <= 2433 398 if (!PyString_Check(obResult)) 434 #else435 if (!PyUnicode_Check(obResult))436 #endif437 399 TRACEBACK_FETCH_ERROR("getvalue() did not return a string\n"); 438 400 439 401 { // a temp scope so I can use temp locals. 440 #if PY_MAJOR_VERSION <= 2441 402 char *tempResult = PyString_AsString(obResult); 442 #else443 char *tempResult = PyUnicode_AsUTF8(obResult);444 #endif445 403 result = (char *)PyMem_Malloc(strlen(tempResult)+1); 446 404 if (result==NULL) -
trunk/src/libs/xpcom18a4/python/src/PyGBase.cpp
r59769 r59795 67 67 PRBool CheckDefaultGateway(PyObject *real_inst, REFNSIID iid, nsISupports **ret_gateway); 68 68 69 /*static*/ nsresult 69 /*static*/ nsresult 70 70 PyG_Base::CreateNew(PyObject *pPyInstance, const nsIID &iid, void **ppResult) 71 71 { … … 115 115 } 116 116 else 117 #if PY_MAJOR_VERSION <= 2118 117 szRepr = PyString_AsString(r); 119 #else120 szRepr = PyUnicode_AsUTF8(r);121 #endif122 118 if (szRepr==NULL) szRepr = ""; 123 119 int reprOffset = *szRepr=='<' ? 1 : 0; … … 189 185 if (iid.Equals(NS_GET_IID(nsISupportsWeakReference))) 190 186 return (nsISupportsWeakReference *)this; 191 if (iid.Equals(NS_GET_IID(nsIInternalPython))) 187 if (iid.Equals(NS_GET_IID(nsIInternalPython))) 192 188 return (nsISupports *)(nsIInternalPython *)this; 193 189 return NULL; … … 196 192 // Call back into Python, passing a Python instance, and get back 197 193 // an interface object that wraps the instance. 198 /*static*/ PRBool 194 /*static*/ PRBool 199 195 PyG_Base::AutoWrapPythonInstance(PyObject *ob, const nsIID &iid, nsISupports **ppret) 200 196 { … … 249 245 // the object to actually use as the gateway parameter for this interface. 250 246 // For example, it is expected that the policy will wrap the interface 251 // object in one of the xpcom.client.Interface objects, allowing 247 // object in one of the xpcom.client.Interface objects, allowing 252 248 // natural usage of the interface from Python clients. 253 249 // Note that piid will usually be NULL - this is because the runtime … … 260 256 // so at least the user can simply QI the object. 261 257 PyObject * 262 PyG_Base::MakeInterfaceParam(nsISupports *pis, 263 const nsIID *piid, 258 PyG_Base::MakeInterfaceParam(nsISupports *pis, 259 const nsIID *piid, 264 260 int methodIndex /* = -1 */, 265 const XPTParamDescriptor *d /* = NULL */, 261 const XPTParamDescriptor *d /* = NULL */, 266 262 int paramIndex /* = -1 */) 267 263 { … … 306 302 goto done; 307 303 308 result = PyObject_CallMethod(m_pPyObject, 304 result = PyObject_CallMethod(m_pPyObject, 309 305 (char*)"_MakeInterfaceParam_", 310 306 (char*)"OOiOi", … … 355 351 return NS_OK; 356 352 } 357 // If we have a "base object", then we need to delegate _every_ remaining 353 // If we have a "base object", then we need to delegate _every_ remaining 358 354 // QI to it. 359 355 if (m_pBaseObject != NULL) … … 378 374 379 375 PyObject *result = PyObject_CallMethod(m_pPyObject, (char*)"_QueryInterface_", 380 (char*)"OO", 376 (char*)"OO", 381 377 this_interface_ob, ob); 382 378 Py_DECREF(ob); … … 466 462 if (PyErr_Occurred()) { 467 463 // The error handling - fairly involved, but worth it as 468 // good error reporting is critical for users to know WTF 464 // good error reporting is critical for users to know WTF 469 465 // is going on - especially with TypeErrors etc in their 470 466 // return values (ie, after the Python code has successfully 471 467 // exited, but we encountered errors unpacking their 472 // result values for the COM caller - there is literally no 468 // result values for the COM caller - there is literally no 473 469 // way to catch these exceptions from Python code, as their 474 470 // is no Python function directly on the call-stack) … … 485 481 PyErr_Fetch(&exc_typ, &exc_val, &exc_tb); 486 482 487 PyObject *err_result = PyObject_CallMethod(m_pPyObject, 483 PyObject *err_result = PyObject_CallMethod(m_pPyObject, 488 484 (char*)"_GatewayException_", 489 485 (char*)"z(OOO)", … … 645 641 ob_ret = PyObject_GetAttrString(real_ob, (char *)szPropertyName); 646 642 if (ob_ret==NULL) { 647 PyErr_Format(PyExc_AttributeError, 648 "The object does not have a 'get_%s' function, or a '%s attribute.", 643 PyErr_Format(PyExc_AttributeError, 644 "The object does not have a 'get_%s' function, or a '%s attribute.", 649 645 szPropertyName, szPropertyName); 650 646 } else { … … 699 695 ret = NS_OK; 700 696 else { 701 PyErr_Format(PyExc_AttributeError, 702 "The object does not have a 'set_%s' function, or a '%s attribute.", 697 PyErr_Format(PyExc_AttributeError, 698 "The object does not have a 'set_%s' function, or a '%s attribute.", 703 699 szPropertyName, szPropertyName); 704 700 } … … 741 737 first thing we do is see if it has been auto-wrapped before. 742 738 743 If not, we create a new wrapper, then make a COM weak reference 739 If not, we create a new wrapper, then make a COM weak reference 744 740 to that wrapper, and store it directly back into the instance 745 741 we are auto-wrapping! The use of a weak-reference prevents … … 765 761 PRBool ok = PR_TRUE; 766 762 nsCOMPtr<nsIWeakReference> pWeakRef; 767 ok = NS_SUCCEEDED(Py_nsISupports::InterfaceFromPyObject(ob_existing_weak, 768 NS_GET_IID(nsIWeakReference), 763 ok = NS_SUCCEEDED(Py_nsISupports::InterfaceFromPyObject(ob_existing_weak, 764 NS_GET_IID(nsIWeakReference), 769 765 getter_AddRefs(pWeakRef), 770 766 PR_FALSE)); … … 795 791 PRBool ok = PR_TRUE; 796 792 nsCOMPtr<nsIWeakReference> pWeakRef; 797 ok = NS_SUCCEEDED(Py_nsISupports::InterfaceFromPyObject(ob_existing_weak, 798 NS_GET_IID(nsIWeakReference), 799 getter_AddRefs(pWeakRef), 793 ok = NS_SUCCEEDED(Py_nsISupports::InterfaceFromPyObject(ob_existing_weak, 794 NS_GET_IID(nsIWeakReference), 795 getter_AddRefs(pWeakRef), 800 796 PR_FALSE)); 801 797 Py_DECREF(ob_existing_weak); … … 831 827 swr->GetWeakReference( getter_AddRefs(pWeakReference) ); 832 828 if (pWeakReference) { 833 PyObject *ob_new_weak = Py_nsISupports::PyObjectFromInterface(pWeakReference, 829 PyObject *ob_new_weak = Py_nsISupports::PyObjectFromInterface(pWeakReference, 834 830 NS_GET_IID(nsIWeakReference), 835 831 PR_FALSE ); /* bMakeNicePyObject */ -
trunk/src/libs/xpcom18a4/python/src/PyIClassInfo.cpp
r59769 r59795 107 107 { 108 108 if (v) 109 #if PY_MAJOR_VERSION <= 2110 109 return PyString_FromString(v); 111 #else112 return PyUnicode_FromString(v);113 #endif114 110 Py_INCREF(Py_None); 115 111 return Py_None; … … 171 167 } 172 168 173 struct PyMethodDef 169 struct PyMethodDef 174 170 PyMethods_IClassInfo[] = 175 171 { -
trunk/src/libs/xpcom18a4/python/src/PyIComponentManagerObsolete.cpp
r59769 r59795 133 133 return PyXPCOM_BuildPyException(r); 134 134 135 #if PY_MAJOR_VERSION <= 2136 135 PyObject *ob_pid = PyString_FromString(ret_pid); 137 136 PyObject *ob_class = PyString_FromString(ret_class); 138 #else139 PyObject *ob_pid = PyUnicode_FromString(ret_pid);140 PyObject *ob_class = PyUnicode_FromString(ret_class);141 #endif142 137 PyObject *ret = Py_BuildValue("OO", ob_pid, ob_class); 143 138 nsMemory::Free(ret_pid); … … 188 183 } 189 184 190 struct PyMethodDef 185 struct PyMethodDef 191 186 PyMethods_IComponentManagerObsolete[] = 192 187 { -
trunk/src/libs/xpcom18a4/python/src/PyIID.cpp
r59769 r59795 60 60 PyObject *obBuf; 61 61 if ( PyArg_ParseTuple(args, "O", &obBuf)) { 62 #if PY_MAJOR_VERSION <= 263 62 if (PyBuffer_Check(obBuf)) { 64 63 PyBufferProcs *pb = NULL; … … 66 65 void *buf = NULL; 67 66 int size = (*pb->bf_getreadbuffer)(obBuf, 0, &buf); 68 #else69 if (PyObject_CheckBuffer(obBuf)) {70 void *buf = NULL;71 Py_buffer view;72 if (PyObject_GetBuffer(obBuf, &view, PyBUF_CONTIG_RO) != 0)73 {74 PyErr_Format(PyExc_ValueError, "Could not get contiguous buffer from object");75 return NULL;76 }77 Py_ssize_t size = view.len;78 buf = view.buf;79 #endif80 67 if (size != sizeof(nsIID) || buf==NULL) { 81 #if PY_MAJOR_VERSION >= 382 PyBuffer_Release(&view);83 #endif84 68 #ifdef VBOX 85 PyErr_Format(PyExc_ValueError, "A buffer object to be converted to an IID must be exactly %d bytes long", (int)sizeof(nsIID));69 PyErr_Format(PyExc_ValueError, "A buffer object to be converted to an IID must be exactly %d bytes long", (int)sizeof(nsIID)); 86 70 #else 87 71 PyErr_Format(PyExc_ValueError, "A buffer object to be converted to an IID must be exactly %d bytes long", sizeof(nsIID)); … … 101 85 ptr += sizeof(PRUint8); 102 86 } 103 #if PY_MAJOR_VERSION >= 3104 PyBuffer_Release(&view);105 #endif106 87 return new Py_nsIID(iid); 107 88 } … … 126 107 return PR_FALSE; 127 108 } 128 #if PY_MAJOR_VERSION <= 2129 109 if (PyString_Check(ob)) { 130 110 ok = iid.Parse(PyString_AsString(ob)); 131 #else132 if (PyUnicode_Check(ob)) {133 ok = iid.Parse(PyUnicode_AsUTF8(ob));134 #endif135 111 if (!ok) { 136 112 PyXPCOM_BuildPyException(NS_ERROR_ILLEGAL_VALUE); … … 168 144 PyTypeObject Py_nsIID::type = 169 145 { 170 PyVarObject_HEAD_INIT(&PyType_Type, 0) 146 PyObject_HEAD_INIT(&PyType_Type) 147 0, 171 148 "IID", 172 149 sizeof(Py_nsIID), … … 176 153 PyTypeMethod_getattr, /* tp_getattr */ 177 154 0, /* tp_setattr */ 178 #if PY_MAJOR_VERSION <= 2179 155 PyTypeMethod_compare, /* tp_compare */ 180 #else181 0, /* reserved */182 #endif183 156 PyTypeMethod_repr, /* tp_repr */ 184 157 0, /* tp_as_number */ … … 188 161 0, /* tp_call */ 189 162 PyTypeMethod_str, /* tp_str */ 190 0, /* tp_getattro */191 0, /* tp_setattro */192 0, /* tp_as_buffer */193 0, /* tp_flags */194 0, /* tp_doc */195 0, /* tp_traverse */196 0, /* tp_clear */197 PyTypeMethod_richcompare, /* tp_richcompare */198 0, /* tp_weaklistoffset */199 0, /* tp_iter */200 0, /* tp_iternext */201 0, /* tp_methods */202 0, /* tp_members */203 0, /* tp_getset */204 0, /* tp_base */205 163 }; 206 164 … … 226 184 PyObject *ret; 227 185 if (iid_repr != nsnull) { 228 #if PY_MAJOR_VERSION <= 2229 186 ret = PyString_FromString(iid_repr); 230 #else231 ret = PyUnicode_FromString(iid_repr);232 #endif233 187 nsMemory::Free(iid_repr); 234 188 } else 235 #if PY_MAJOR_VERSION <= 2236 189 ret = PyString_FromString("<cant get IID info!>"); 237 #else238 ret = PyUnicode_FromString("<cant get IID info!>");239 #endif240 190 return ret; 241 191 } … … 243 193 } 244 194 245 #if PY_MAJOR_VERSION <= 2246 195 /* static */ int 247 196 Py_nsIID::PyTypeMethod_compare(PyObject *self, PyObject *other) … … 252 201 return rc == 0 ? 0 : (rc < 0 ? -1 : 1); 253 202 } 254 #endif255 256 /* static */ PyObject *257 Py_nsIID::PyTypeMethod_richcompare(PyObject *self, PyObject *other, int op)258 {259 PyObject *result = NULL;260 Py_nsIID *s_iid = (Py_nsIID *)self;261 Py_nsIID *o_iid = (Py_nsIID *)other;262 int rc = memcmp(&s_iid->m_iid, &o_iid->m_iid, sizeof(s_iid->m_iid));263 switch (op)264 {265 case Py_LT:266 result = rc < 0 ? Py_True : Py_False;267 break;268 case Py_LE:269 result = rc <= 0 ? Py_True : Py_False;270 break;271 case Py_EQ:272 result = rc == 0 ? Py_True : Py_False;273 break;274 case Py_NE:275 result = rc != 0 ? Py_True : Py_False;276 break;277 case Py_GT:278 result = rc > 0 ? Py_True : Py_False;279 break;280 case Py_GE:281 result = rc >= 0 ? Py_True : Py_False;282 break;283 }284 Py_XINCREF(result);285 return result;286 }287 203 288 204 /* static */ PyObject * … … 293 209 char *sziid = s_iid->m_iid.ToString(); 294 210 #ifdef VBOX 295 snprintf(buf, sizeof(buf), "_xpcom.I D('%s')", sziid);211 snprintf(buf, sizeof(buf), "_xpcom.IID('%s')", sziid); 296 212 #else 297 213 sprintf(buf, "_xpcom.IID('%s')", sziid); 298 214 #endif 299 215 nsMemory::Free(sziid); 300 #if PY_MAJOR_VERSION <= 2301 216 return PyString_FromString(buf); 302 #else303 return PyUnicode_FromString(buf);304 #endif305 217 } 306 218 … … 310 222 Py_nsIID *s_iid = (Py_nsIID *)self; 311 223 char *sziid = s_iid->m_iid.ToString(); 312 #if PY_MAJOR_VERSION <= 2313 224 PyObject *ret = PyString_FromString(sziid); 314 #else315 PyObject *ret = PyUnicode_FromString(sziid);316 #endif317 225 nsMemory::Free(sziid); 318 226 return ret; -
trunk/src/libs/xpcom18a4/python/src/PyIInputStream.cpp
r59769 r59795 109 109 } 110 110 if (n==0) { // mozilla will assert if we alloc zero bytes. 111 #if PY_MAJOR_VERSION <= 2112 111 return PyBuffer_New(0); 113 #else114 return PyBytes_FromString("");115 #endif116 112 } 117 113 char *buf = (char *)nsMemory::Alloc(n); … … 127 123 PyObject *rc = NULL; 128 124 if ( NS_SUCCEEDED(r) ) { 129 #if PY_MAJOR_VERSION <= 2130 125 rc = PyBuffer_New(nread); 131 126 if (rc != NULL) { … … 151 146 memcpy(ob_buf, buf, nread); 152 147 } 153 #else154 rc = PyBytes_FromStringAndSize(buf, nread);155 #endif156 148 } else 157 149 PyXPCOM_BuildPyException(r); -
trunk/src/libs/xpcom18a4/python/src/PyIInterfaceInfo.cpp
r59769 r59795 75 75 if ( NS_FAILED(r) ) 76 76 return PyXPCOM_BuildPyException(r); 77 #if PY_MAJOR_VERSION <= 278 77 PyObject *ret = PyString_FromString(name); 79 #else80 PyObject *ret = PyUnicode_FromString(name);81 #endif82 78 nsMemory::Free(name); 83 79 return ret; … … 397 393 } 398 394 399 struct PyMethodDef 395 struct PyMethodDef 400 396 PyMethods_IInterfaceInfo[] = 401 397 { -
trunk/src/libs/xpcom18a4/python/src/PyIInterfaceInfoManager.cpp
r59769 r59795 135 135 return PyXPCOM_BuildPyException(r); 136 136 137 #if PY_MAJOR_VERSION <= 2138 137 PyObject *ret = PyString_FromString(ret_name); 139 #else140 PyObject *ret = PyUnicode_FromString(ret_name);141 #endif142 138 nsMemory::Free(ret_name); 143 139 return ret; … … 190 186 // void autoRegisterInterfaces(); 191 187 192 PyMethodDef 188 PyMethodDef 193 189 PyMethods_IInterfaceInfoManager[] = 194 190 { -
trunk/src/libs/xpcom18a4/python/src/PyISupports.cpp
r59769 r59795 218 218 } 219 219 PyXPCOM_TypeObject *this_type = (PyXPCOM_TypeObject *)ob_type; 220 #if PY_MAJOR_VERSION <= 2221 220 return Py_FindMethodInChain(&this_type->chain, this, (char *)name); 222 #else223 PyMethodChain *chain = &this_type->chain;224 if (name[0] == '_' && name[1] == '_')225 {226 if (!strcmp(name, "__doc__"))227 {228 const char *doc = ob_type->tp_doc;229 if (doc)230 #if PY_MAJOR_VERSION <= 2231 return PyString_FromString(doc);232 #else233 return PyUnicode_FromString(doc);234 #endif235 }236 }237 while (chain)238 {239 PyMethodDef *ml = chain->methods;240 for (; ml->ml_name; ml++)241 {242 if (!strcmp(name, ml->ml_name))243 return PyCFunction_New(ml, this);244 }245 chain = chain->link;246 }247 PyErr_SetString(PyExc_AttributeError, name);248 return NULL;249 #endif250 221 } 251 222 -
trunk/src/libs/xpcom18a4/python/src/PyIVariant.cpp
r59769 r59795 62 62 } 63 63 static PyObject *MyChar( char c) { 64 #if PY_MAJOR_VERSION <= 265 64 return PyString_FromStringAndSize(&c, 1); 66 #else67 return PyUnicode_FromStringAndSize(&c, 1);68 #endif69 65 } 70 66 static PyObject *MyUChar( PRUnichar c) { … … 127 123 GET_SIMPLE(nsIID, GetAsID, Py_nsIID::PyObjectFromIID) 128 124 129 #if PY_MAJOR_VERSION <= 2130 125 GET_ALLOCATED(char *, GetAsString, PyString_FromString, nsMemory::Free) 131 #else132 GET_ALLOCATED(char *, GetAsString, PyUnicode_FromString, nsMemory::Free)133 #endif134 126 GET_ALLOCATED(PRUnichar *, GetAsWString, MyUnicode, nsMemory::Free) 135 #if PY_MAJOR_VERSION <= 2136 127 GET_ALLOCATED_SIZE(char *, GetAsStringWithSize, PyString_FromStringAndSize, nsMemory::Free) 137 #else138 GET_ALLOCATED_SIZE(char *, GetAsStringWithSize, PyUnicode_FromStringAndSize, nsMemory::Free)139 #endif140 128 GET_ALLOCATED_SIZE(PRUnichar *, GetAsWStringWithSize, PyObject_FromNSString, nsMemory::Free) 141 129 … … 178 166 } 179 167 180 struct PyMethodDef 168 struct PyMethodDef 181 169 PyMethods_IVariant[] = 182 170 { -
trunk/src/libs/xpcom18a4/python/src/PyXPCOM.h
r59769 r59795 133 133 # endif 134 134 135 # if PY_MAJOR_VERSION >= 3136 # 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_AsUTF8141 # define PyUnicode_AsUTF8(o) _PyUnicode_AsString(o)142 # endif143 # ifndef PyUnicode_AsUTF8AndSize144 # define PyUnicode_AsUTF8AndSize(o,s) _PyUnicode_AsStringAndSize(o,s)145 # endif146 typedef struct PyMethodChain147 {148 PyMethodDef *methods;149 struct PyMethodChain *link;150 } PyMethodChain;151 # endif152 153 135 #endif /* VBOX_PYXPCOM */ 154 136 … … 286 268 static int Py_setattr(PyObject *op, char *name, PyObject *v); 287 269 static int Py_cmp(PyObject *ob1, PyObject *ob2); 288 static PyObject *Py_richcmp(PyObject *ob1, PyObject *ob2, int op);289 270 static long Py_hash(PyObject *self); 290 271 }; … … 438 419 /* Python support */ 439 420 static PyObject *PyTypeMethod_getattr(PyObject *self, char *name); 440 #if PY_MAJOR_VERSION <= 2441 421 static int PyTypeMethod_compare(PyObject *self, PyObject *ob); 442 #endif443 static PyObject *PyTypeMethod_richcompare(PyObject *self, PyObject *ob, int op);444 422 static PyObject *PyTypeMethod_repr(PyObject *self); 445 423 static long PyTypeMethod_hash(PyObject *self); -
trunk/src/libs/xpcom18a4/python/src/Pyxpt_info.cpp
r59769 r59795 55 55 } 56 56 // build an object using the same format as a TypeDescriptor. 57 return Py_BuildValue("bzzz", 57 return Py_BuildValue("bzzz", 58 58 d->flags, 59 59 NULL, NULL, NULL); … … 66 66 return Py_None; 67 67 } 68 return Py_BuildValue("bbbh", 68 return Py_BuildValue("bbbh", 69 69 d->prefix.flags, 70 70 d->argnum, … … 150 150 break; 151 151 case TD_CHAR: 152 #if PY_MAJOR_VERSION <= 2153 152 v = PyString_FromStringAndSize(&c->value.ch, 1); 154 #else155 v = PyUnicode_FromStringAndSize(&c->value.ch, 1);156 #endif157 153 break; 158 154 case TD_WCHAR: 159 155 v = PyObject_FromNSString((PRUnichar *)&c->value.wch, 1); 160 156 break; 161 // TD_VOID = 13, 157 // TD_VOID = 13, 162 158 case TD_PNSIID: 163 159 v = Py_nsIID::PyObjectFromIID(*c->value.iid); … … 165 161 // TD_DOMSTRING = 15, 166 162 case TD_PSTRING: 167 #if PY_MAJOR_VERSION <= 2168 163 v = PyString_FromString(c->value.str); 169 #else170 v = PyUnicode_FromString(c->value.str);171 #endif172 164 break; 173 165 case TD_PWSTRING: … … 183 175 // TD_ASTRING = 25 184 176 default: 185 #if PY_MAJOR_VERSION <= 2186 177 v = PyString_FromString("Unknown type code!!"); 187 #else188 v = PyUnicode_FromString("Unknown type code!!");189 #endif190 178 break; 191 179 -
trunk/src/libs/xpcom18a4/python/src/TypeObject.cpp
r59769 r59795 53 53 54 54 static PyTypeObject PyInterfaceType_Type = { 55 PyVarObject_HEAD_INIT(&PyType_Type, 0) 55 PyObject_HEAD_INIT(&PyType_Type) 56 0, /* Number of items for varobject */ 56 57 "interface-type", /* Name of this type */ 57 58 sizeof(PyTypeObject), /* Basic object size */ … … 79 80 PyXPCOM_TypeObject::IsType(PyTypeObject *t) 80 81 { 81 #if PY_MAJOR_VERSION <= 282 82 return t->ob_type == &PyInterfaceType_Type; 83 #else84 return Py_TYPE(t) == &PyInterfaceType_Type;85 #endif86 83 } 87 84 … … 125 122 } 126 123 127 /*static*/PyObject *128 PyXPCOM_TypeObject::Py_richcmp(PyObject *self, PyObject *other, int op)129 {130 PyObject *result = NULL;131 int rc = Py_cmp(self, other);132 switch (op)133 {134 case Py_LT:135 result = rc < 0 ? Py_True : Py_False;136 break;137 case Py_LE:138 result = rc <= 0 ? Py_True : Py_False;139 break;140 case Py_EQ:141 result = rc == 0 ? Py_True : Py_False;142 break;143 case Py_NE:144 result = rc != 0 ? Py_True : Py_False;145 break;146 case Py_GT:147 result = rc > 0 ? Py_True : Py_False;148 break;149 case Py_GE:150 result = rc >= 0 ? Py_True : Py_False;151 break;152 }153 Py_XINCREF(result);154 return result;155 }156 157 124 // @pymethod int|Py_nsISupports|__hash__|Implement a hash-code for the XPCOM object using XPCOM identity rules. 158 125 /*static*/long PyXPCOM_TypeObject::Py_hash(PyObject *self) … … 185 152 char buf[512]; 186 153 #ifdef VBOX 187 snprintf(buf, sizeof(buf), "<XPCOM object (%s) at %p/%p>",154 snprintf(buf, sizeof(buf), "<XPCOM object (%s) at 0x%p/0x%p>", 188 155 iid_repr, (void *)self, (void *)pis->m_obj.get()); 189 156 #else … … 192 159 #endif 193 160 nsMemory::Free(iid_repr); 194 #if PY_MAJOR_VERSION <= 2195 161 return PyString_FromString(buf); 196 #else197 return PyUnicode_FromString(buf);198 #endif199 162 } 200 163 … … 210 173 if (NS_SUCCEEDED(rv)) 211 174 rv = ss->ToString(&val); 212 } // end-scope 175 } // end-scope 213 176 Py_END_ALLOW_THREADS; 214 177 PyObject *ret; … … 216 179 ret = Py_repr(self); 217 180 else 218 #if PY_MAJOR_VERSION <= 2219 181 ret = PyString_FromString(val); 220 #else221 ret = PyUnicode_FromString(val);222 #endif223 182 if (val) nsMemory::Free(val); 224 183 return ret; … … 234 193 { 235 194 static const PyTypeObject type_template = { 236 PyVarObject_HEAD_INIT(&PyInterfaceType_Type, 0) 195 PyObject_HEAD_INIT(&PyInterfaceType_Type) 196 0, /*ob_size*/ 237 197 "XPCOMTypeTemplate", /*tp_name*/ 238 sizeof(Py_nsISupports), /*tp_basicsize*/198 sizeof(Py_nsISupports), /*tp_basicsize*/ 239 199 0, /*tp_itemsize*/ 240 200 Py_dealloc, /* tp_dealloc */ … … 242 202 Py_getattr, /* tp_getattr */ 243 203 Py_setattr, /* tp_setattr */ 244 #if PY_MAJOR_VERSION <= 2245 204 Py_cmp, /* tp_compare */ 246 #else247 0, /* reserved */248 #endif249 205 Py_repr, /* tp_repr */ 250 0, /* tp_as_number*/206 0, /* tp_as_number*/ 251 207 0, /* tp_as_sequence */ 252 208 0, /* tp_as_mapping */ … … 255 211 Py_str, /* tp_str */ 256 212 0, /* tp_getattro */ 257 0, /* tp_setattro */213 0, /*tp_setattro */ 258 214 0, /* tp_as_buffer */ 259 215 0, /* tp_flags */ … … 261 217 0, /* tp_traverse */ 262 218 0, /* tp_clear */ 263 Py_richcmp,/* tp_richcompare */219 0, /* tp_richcompare */ 264 220 0, /* tp_weaklistoffset */ 265 221 0, /* tp_iter */ -
trunk/src/libs/xpcom18a4/python/src/VariantUtils.cpp
r59769 r59795 84 84 PRUint32 size; 85 85 PyObject *s; 86 void *src;87 86 PRUnichar *dest; 88 87 … … 90 89 if (!s) 91 90 return -1; 92 // Drop the UTF-16 byte order mark at the beginning of93 // the string. (See the docs on PyUnicode_AsUTF16String.)94 // Some Mozilla libraries don't like the mark.95 #if PY_MAJOR_VERSION <= 296 91 size = (PyString_GET_SIZE(s) - 2) / sizeof(PRUnichar); 97 src = PyString_AS_STRING(s) + 2;98 #else99 if (!PyBytes_Check(obj))100 {101 PyErr_SetString(PyExc_TypeError, "internal error in PyXPCOM, parameter must be a bytes object");102 return -1;103 }104 size = (PyBytes_GET_SIZE(obj) - 2) / sizeof(PRUnichar);105 src = PyBytes_AS_STRING(obj) + 2;106 #endif107 92 dest = (PRUnichar *)nsMemory::Alloc(sizeof(PRUnichar) * (size + 1)); 108 93 if (!dest) { … … 111 96 return -1; 112 97 } 113 memcpy(dest, src, sizeof(PRUnichar) * size); 98 // Drop the UTF-16 byte order mark at the beginning of 99 // the string. (See the docs on PyUnicode_AsUTF16String.) 100 // Some Mozilla libraries don't like the mark. 101 memcpy(dest, PyString_AS_STRING(s) + 2, sizeof(PRUnichar) * size); 114 102 Py_DECREF(s); 115 103 dest[size] = 0; … … 128 116 } else { 129 117 if (bAssumeUTF8) { 130 const nsPromiseFlatCString& temp = PromiseFlatCString(s);131 ret = PyUnicode_DecodeUTF8(temp.get(), temp.Length(), NULL);118 const nsPromiseFlatCString& temp = PromiseFlatCString(s); 119 ret = PyUnicode_DecodeUTF8(temp.get(), temp.Length(), NULL); 132 120 } else { 133 #if PY_MAJOR_VERSION <= 2134 121 ret = PyString_FromStringAndSize(NULL, s.Length()); 135 #else136 ret = PyUnicode_FromStringAndSize(NULL, s.Length());137 #endif138 122 if (!ret) 139 123 return NULL; 140 124 // Need "CopyAsciiTo"!? 141 125 nsACString::const_iterator fromBegin, fromEnd; 142 #if PY_MAJOR_VERSION <= 2 143 char* dest = (char *)PyString_AS_STRING(ret); 144 #else 145 char* dest = (char *)PyUnicode_AsUTF8(ret); 146 #endif 126 char* dest = PyString_AS_STRING(ret); 147 127 copy_string(s.BeginReading(fromBegin), s.EndReading(fromEnd), dest); 148 128 } … … 179 159 PyObject *val_use = NULL; 180 160 PRBool ok = PR_TRUE; 181 #if PY_MAJOR_VERSION <= 2182 161 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 183 162 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 186 165 if (ok && (val_use = PyUnicode_FromObject(val))==NULL) 187 166 ok = PR_FALSE; 188 #else189 if (!PyUnicode_Check(val)) {190 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");191 ok = PR_FALSE;192 }193 val_use = val;194 Py_INCREF(val_use);195 #endif196 167 if (ok) { 197 168 if (PyUnicode_GET_SIZE(val_use) == 0) { … … 382 353 // If it is NOT a string, we just fall through and allow the standard 383 354 // sequence unpack code process it (just slower!) 384 #if PY_MAJOR_VERSION <= 2385 355 if ( array_type == nsXPTType::T_U8 && 386 356 (PyString_Check(sequence_ob) || PyUnicode_Check(sequence_ob))) { 387 #else388 if ( array_type == nsXPTType::T_U8 && PyUnicode_Check(sequence_ob)) {389 #endif390 357 391 358 PRBool release_seq; 392 359 if (PyUnicode_Check(sequence_ob)) { 393 360 release_seq = PR_TRUE; 394 #if PY_MAJOR_VERSION <= 2395 361 sequence_ob = PyObject_Str(sequence_ob); 396 #else397 sequence_ob = PyUnicode_AsUTF8String(sequence_ob);398 #endif399 362 } else 400 363 release_seq = PR_FALSE; 401 364 if (!sequence_ob) // presumably a memory error, or Unicode encoding error. 402 365 return PR_FALSE; 403 #if PY_MAJOR_VERSION <= 2404 366 memcpy(pthis, PyString_AS_STRING(sequence_ob), sequence_size); 405 #else406 memcpy(pthis, PyUnicode_AsUTF8(sequence_ob), sequence_size);407 #endif408 367 if (release_seq) 409 368 { … … 464 423 break; 465 424 case nsXPTType::T_CHAR: 466 #if PY_MAJOR_VERSION <= 2467 425 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 468 426 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 474 432 NS_ABORT_IF_FALSE(PyString_Check(val_use), "PyObject_Str didnt return a string object!"); 475 433 FILL_SIMPLE_POINTER( char, *PyString_AS_STRING(val_use) ); 476 #else477 if (!PyUnicode_Check(val)) {478 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");479 BREAK_FALSE;480 }481 FILL_SIMPLE_POINTER( char, *PyUnicode_AsUTF8(val) );482 #endif483 434 break; 484 435 485 436 case nsXPTType::T_WCHAR: 486 #if PY_MAJOR_VERSION <= 2487 437 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 488 438 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); 489 439 BREAK_FALSE; 490 440 } 491 #else492 if (!PyUnicode_Check(val)) {493 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");494 BREAK_FALSE;495 }496 #endif497 441 if ((val_use = PyUnicode_FromObject(val)) == NULL) 498 442 BREAK_FALSE; … … 530 474 if (val == Py_None) 531 475 break; // Remains NULL. 532 #if PY_MAJOR_VERSION <= 2533 476 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 534 477 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 542 485 const char *sz = PyString_AS_STRING(val_use); 543 486 int nch = PyString_GET_SIZE(val_use); 544 #else545 if (!PyUnicode_Check(val)) {546 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");547 BREAK_FALSE;548 }549 if ((val_use = PyUnicode_AsUTF8String(val))==NULL)550 BREAK_FALSE;551 552 const char *sz = PyBytes_AS_STRING(val_use);553 int nch = PyBytes_GET_SIZE(val_use);554 #endif555 487 556 488 *pp = (char *)nsMemory::Alloc(nch+1); … … 570 502 if (val == Py_None) 571 503 break; // Remains NULL. 572 #if PY_MAJOR_VERSION <= 2573 504 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 574 505 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 578 509 BREAK_FALSE; 579 510 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyUnicode_FromObject didnt return a Unicode object!"); 580 #else581 if (!PyUnicode_Check(val)) {582 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");583 BREAK_FALSE;584 }585 val_use = val;586 Py_INCREF(val_use);587 #endif588 511 if (PyUnicode_AsPRUnichar(val_use, pp, NULL) < 0) 589 512 BREAK_FALSE; … … 626 549 } 627 550 if (array_type == nsXPTType::T_U8) 628 #if PY_MAJOR_VERSION <= 2629 551 return PyString_FromStringAndSize( (char *)array_ptr, sequence_size ); 630 #else631 return PyUnicode_FromStringAndSize( (char *)array_ptr, sequence_size );632 #endif633 552 634 553 PRUint32 array_element_size = GetArrayElementSize(array_type); … … 680 599 val = Py_None; 681 600 } else 682 #if PY_MAJOR_VERSION <= 2683 601 val = PyString_FromString(*pp); 684 #else685 val = PyUnicode_FromString(*pp);686 #endif687 602 break; 688 603 } … … 717 632 sprintf(buf, "Unknown XPCOM array type flags (0x%x)", array_type); 718 633 PyXPCOM_LogWarning("%s - returning a string object with this message!\n", buf); 719 #if PY_MAJOR_VERSION <= 2720 634 val = PyString_FromString(buf); 721 #else722 val = PyUnicode_FromString(buf);723 #endif724 635 break; 725 636 } … … 759 670 if (PyFloat_Check(ob)) 760 671 return nsIDataType::VTYPE_DOUBLE; 761 #if PY_MAJOR_VERSION <= 2762 672 if (PyString_Check(ob)) 763 673 return nsIDataType::VTYPE_STRING_SIZE_IS; 764 #endif765 674 if (PyUnicode_Check(ob)) 766 675 return nsIDataType::VTYPE_WSTRING_SIZE_IS; … … 817 726 break; 818 727 case nsIDataType::VTYPE_STRING_SIZE_IS: 819 #if PY_MAJOR_VERSION <= 2820 728 nr = v->SetAsStringWithSize(PyString_Size(ob), PyString_AsString(ob)); 821 #else822 Py_ssize_t cb;823 const char *psz;824 psz = PyUnicode_AsUTF8AndSize(ob, &cb);825 nr = v->SetAsStringWithSize(cb, psz);826 #endif827 729 break; 828 730 case nsIDataType::VTYPE_WSTRING_SIZE_IS: … … 1394 1296 break; 1395 1297 case nsXPTType::T_CHAR:{ 1396 #if PY_MAJOR_VERSION <= 21397 1298 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 1398 1299 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 1409 1310 1410 1311 ns_v.val.c = *PyString_AS_STRING(val_use); 1411 #else1412 if (!PyUnicode_Check(val)) {1413 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1414 BREAK_FALSE;1415 }1416 if (PyUnicode_GET_SIZE(val) != 1) {1417 PyErr_SetString(PyExc_ValueError, "Must specify a one character string for a character");1418 BREAK_FALSE;1419 }1420 1421 ns_v.val.c = *PyUnicode_AS_UNICODE(val_use);1422 #endif1423 1312 break; 1424 1313 } 1425 1314 1426 1315 case nsXPTType::T_WCHAR: { 1427 #if PY_MAJOR_VERSION <= 21428 1316 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 1429 1317 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); 1430 1318 BREAK_FALSE; 1431 1319 } 1432 #else1433 if (!PyUnicode_Check(val)) {1434 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1435 BREAK_FALSE;1436 }1437 #endif1438 1320 if ((val_use = PyUnicode_FromObject(val))==NULL) 1439 1321 BREAK_FALSE; 1440 // Sanity check should Py Unicode_FromObject() ever loosen its semantics wrt Unicode!1322 // Sanity check should PyObject_Str() ever loosen its semantics wrt Unicode! 1441 1323 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyUnicode_FromObject didnt return a unicode object!"); 1442 if (PyUnicode_G ET_SIZE(val_use) != 1) {1324 if (PyUnicode_GetSize(val_use) != 1) { 1443 1325 PyErr_SetString(PyExc_ValueError, "Must specify a one character string for a character"); 1444 1326 BREAK_FALSE; … … 1478 1360 ns_v.val.p = new nsCString(); 1479 1361 } else { 1480 #if PY_MAJOR_VERSION <= 2 1362 // strings are assumed to already be UTF8 encoded. 1481 1363 if (PyString_Check(val)) { 1482 // strings are assumed to already be UTF8 encoded.1483 1364 val_use = val; 1484 1365 Py_INCREF(val); 1485 } 1486 else 1487 #endif 1488 if (PyUnicode_Check(val)) { 1489 // Unicode objects are encoded by us. 1366 // Unicode objects are encoded by us. 1367 } else if (PyUnicode_Check(val)) { 1490 1368 if (bIsUTF8) 1491 1369 val_use = PyUnicode_AsUTF8String(val); 1492 1370 else 1493 #if PY_MAJOR_VERSION <= 21494 1371 val_use = PyObject_Str(val); 1495 #else1496 val_use = PyUnicode_AsUTF8String(val);1497 #endif1498 1372 } else { 1499 #if PY_MAJOR_VERSION <= 21500 1373 PyErr_SetString(PyExc_TypeError, "UTF8 parameters must be string or Unicode objects"); 1501 #else1502 PyErr_SetString(PyExc_TypeError, "UTF8 parameters must be unicode objects");1503 #endif1504 1374 BREAK_FALSE; 1505 1375 } 1506 1376 if (!val_use) 1507 1377 BREAK_FALSE; 1508 #if PY_MAJOR_VERSION <= 21509 1378 ns_v.val.p = new nsCString(PyString_AS_STRING(val_use), 1510 1379 PyString_GET_SIZE(val_use)); 1511 #else1512 ns_v.val.p = new nsCString(PyBytes_AS_STRING(val_use),1513 PyBytes_GET_SIZE(val_use));1514 #endif1515 1380 } 1516 1381 … … 1528 1393 break; 1529 1394 } 1530 #if PY_MAJOR_VERSION <= 21531 1395 // If an "in" char *, and we have a PyString, then pass the 1532 1396 // pointer (hoping everyone else plays by the rules too. 1533 1397 if (!XPT_PD_IS_OUT(td.param_flags) && PyString_Check(val)) { 1534 ns_v.val.p = (void *)PyString_AS_STRING(val);1398 ns_v.val.p = PyString_AS_STRING(val); 1535 1399 break; 1536 1400 } … … 1548 1412 MAKE_VALUE_BUFFER(cb_this_buffer_pointer); 1549 1413 memcpy(this_buffer_pointer, PyString_AS_STRING(val_use), cb_this_buffer_pointer); 1550 #else1551 1552 if (!PyUnicode_Check(val)) {1553 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1554 BREAK_FALSE;1555 }1556 if ((val_use = PyUnicode_AsUTF8String(val))==NULL)1557 BREAK_FALSE;1558 1559 cb_this_buffer_pointer = PyBytes_GET_SIZE(val_use)+1;1560 MAKE_VALUE_BUFFER(cb_this_buffer_pointer);1561 memcpy(this_buffer_pointer, PyBytes_AS_STRING(val_use), cb_this_buffer_pointer);1562 #endif1563 1414 ns_v.val.p = this_buffer_pointer; 1564 1415 break; … … 1570 1421 break; 1571 1422 } 1572 #if PY_MAJOR_VERSION <= 21573 1423 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 1574 1424 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 1578 1428 BREAK_FALSE; 1579 1429 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyUnicode_FromObject didnt return a Unicode object!"); 1580 #else1581 if (!PyUnicode_Check(val)) {1582 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1583 BREAK_FALSE;1584 }1585 val_use = val;1586 Py_INCREF(val_use);1587 #endif1588 1430 PRUnichar *sv; 1589 1431 PRUint32 nch; … … 1642 1484 break; 1643 1485 } 1644 #if PY_MAJOR_VERSION <= 21645 1486 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 1646 1487 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 1655 1496 MAKE_VALUE_BUFFER(cb_this_buffer_pointer); 1656 1497 memcpy(this_buffer_pointer, PyString_AS_STRING(val_use), cb_this_buffer_pointer); 1657 #else1658 if (!PyUnicode_Check(val)) {1659 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1660 BREAK_FALSE;1661 }1662 if ((val_use = PyUnicode_AsUTF8String(val))==NULL)1663 BREAK_FALSE;1664 1665 cb_this_buffer_pointer = PyBytes_GET_SIZE(val_use);1666 MAKE_VALUE_BUFFER(cb_this_buffer_pointer);1667 memcpy(this_buffer_pointer, PyBytes_AS_STRING(val_use), cb_this_buffer_pointer);1668 #endif1669 1498 ns_v.val.p = this_buffer_pointer; 1670 1499 rc = SetSizeIs(value_index, PR_TRUE, cb_this_buffer_pointer); … … 1677 1506 break; 1678 1507 } 1679 #if PY_MAJOR_VERSION <= 21680 1508 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 1681 1509 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 1686 1514 // Sanity check should PyObject_Str() ever loosen its semantics wrt Unicode! 1687 1515 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyObject_Unicode didnt return a unicode object!"); 1688 #else1689 if (!PyUnicode_Check(val)) {1690 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");1691 BREAK_FALSE;1692 }1693 val_use = val;1694 Py_INCREF(val_use);1695 #endif1696 1516 PRUnichar *sv; 1697 1517 PRUint32 nch; … … 1899 1719 break; 1900 1720 case nsXPTType::T_CHAR: 1901 #if PY_MAJOR_VERSION <= 21902 1721 ret = PyString_FromStringAndSize( ((char *)ns_v.ptr), 1 ); 1903 #else1904 ret = PyUnicode_FromStringAndSize( ((char *)ns_v.ptr), 1 );1905 #endif1906 1722 break; 1907 1723 … … 1931 1747 Py_INCREF(Py_None); 1932 1748 } else 1933 #if PY_MAJOR_VERSION <= 21934 1749 ret = PyString_FromString( *((char **)ns_v.ptr) ); 1935 #else1936 ret = PyUnicode_FromString( *((char **)ns_v.ptr) );1937 #endif1938 1750 break; 1939 1751 … … 2016 1828 } else { 2017 1829 PRUint32 string_size = GetSizeIs(index, PR_TRUE); 2018 #if PY_MAJOR_VERSION <= 22019 1830 ret = PyString_FromStringAndSize( *((char **)ns_v.ptr), string_size ); 2020 #else2021 ret = PyUnicode_FromStringAndSize( *((char **)ns_v.ptr), string_size );2022 #endif2023 1831 } 2024 1832 break; … … 2275 2083 case nsXPTType::T_CHAR: { 2276 2084 char temp = DEREF_IN_OR_OUT(ns_v.val.c, char); 2277 #if PY_MAJOR_VERSION <= 22278 2085 ret = PyString_FromStringAndSize(&temp, 1); 2279 #else2280 ret = PyUnicode_FromStringAndSize(&temp, 1);2281 #endif2282 2086 break; 2283 2087 } … … 2312 2116 Py_INCREF(Py_None); 2313 2117 } else 2314 #if PY_MAJOR_VERSION <= 22315 2118 ret = PyString_FromString(t); 2316 #else2317 ret = PyUnicode_FromString(t);2318 #endif2319 2119 break; 2320 2120 } … … 2378 2178 Py_INCREF(Py_None); 2379 2179 } else 2380 #if PY_MAJOR_VERSION <= 22381 2180 ret = PyString_FromStringAndSize(t, string_size); 2382 #else2383 ret = PyUnicode_FromStringAndSize(t, string_size);2384 #endif2385 2181 break; 2386 2182 } … … 2403 2199 sprintf(buf, "Unknown XPCOM type flags (0x%x)", td.type_flags); 2404 2200 PyXPCOM_LogWarning("%s - returning a string object with this message!\n", buf); 2405 #if PY_MAJOR_VERSION <= 22406 2201 ret = PyString_FromString(buf); 2407 #else2408 ret = PyUnicode_FromString(buf);2409 #endif2410 2202 break; 2411 2203 } … … 2548 2340 break; 2549 2341 case nsXPTType::T_CHAR: 2550 #if PY_MAJOR_VERSION <= 22551 2342 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2552 2343 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2558 2349 NS_ABORT_IF_FALSE(PyString_Check(val_use), "PyObject_Str didnt return a string object!"); 2559 2350 FILL_SIMPLE_POINTER( char, *PyString_AS_STRING(val_use) ); 2560 #else2561 if (!PyUnicode_Check(val)) {2562 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");2563 BREAK_FALSE;2564 }2565 FILL_SIMPLE_POINTER( char, *PyUnicode_AS_UNICODE(val) );2566 #endif2567 2351 break; 2568 2352 2569 2353 case nsXPTType::T_WCHAR: 2570 #if PY_MAJOR_VERSION <= 22571 2354 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2572 2355 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); 2573 2356 BREAK_FALSE; 2574 2357 } 2575 #else2576 if (!PyUnicode_Check(val)) {2577 PyErr_SetString(PyExc_TypeError, "This parameter must be a Unicode object");2578 BREAK_FALSE;2579 }2580 #endif2581 2358 if ((val_use = PyUnicode_FromObject(val))==NULL) 2582 2359 BREAK_FALSE; … … 2618 2395 NS_ABORT_IF_FALSE(0, "dont handle None here yet"); 2619 2396 } else { 2620 #if PY_MAJOR_VERSION <= 22621 2397 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2622 2398 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2626 2402 NS_ABORT_IF_FALSE(PyString_Check(val_use), "PyObject_Str didnt return a string object!"); 2627 2403 const char *sz = PyString_AS_STRING(val_use); 2628 ws->Assign(sz, PyString_GET_SIZE(val_use)); 2629 #else 2630 if (!PyUnicode_Check(val)) { 2631 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object"); 2632 BREAK_FALSE; 2633 } 2634 val_use = PyUnicode_AsUTF8String(val); 2635 const char *sz = PyBytes_AS_STRING(val_use); 2636 ws->Assign(sz, PyBytes_GET_SIZE(val_use)); 2637 #endif 2404 ws->Assign(sz, PyString_Size(val_use)); 2638 2405 } 2639 2406 break; … … 2645 2412 NS_ABORT_IF_FALSE(0, "dont handle None here yet"); 2646 2413 } else { 2647 #if PY_MAJOR_VERSION <= 22648 2414 if (PyString_Check(val)) { 2649 2415 val_use = val; 2650 2416 Py_INCREF(val); 2651 } 2652 else 2653 #endif 2654 if (PyUnicode_Check(val)) { 2417 } else if (PyUnicode_Check(val)) { 2655 2418 val_use = PyUnicode_AsUTF8String(val); 2656 2419 } else { 2657 #if PY_MAJOR_VERSION <= 22658 2420 PyErr_SetString(PyExc_TypeError, "UTF8 parameters must be string or Unicode objects"); 2659 #else 2660 PyErr_SetString(PyExc_TypeError, "UTF8 parameters must be unicode objects"); 2661 #endif 2662 BREAK_FALSE; 2663 } 2664 #if PY_MAJOR_VERSION <= 2 2421 BREAK_FALSE; 2422 } 2665 2423 NS_ABORT_IF_FALSE(PyString_Check(val_use), "must have a string object!"); 2666 2424 const char *sz = PyString_AS_STRING(val_use); 2667 ws->Assign(sz, PyString_GET_SIZE(val_use)); 2668 #else 2669 NS_ABORT_IF_FALSE(PyBytes_Check(val_use), "must have a bytes object!"); 2670 const char *sz = PyBytes_AS_STRING(val_use); 2671 ws->Assign(sz, PyBytes_GET_SIZE(val_use)); 2672 #endif 2425 ws->Assign(sz, PyString_Size(val_use)); 2673 2426 } 2674 2427 break; … … 2684 2437 if (val == Py_None) 2685 2438 break; // Remains NULL. 2686 #if PY_MAJOR_VERSION <= 22687 2439 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2688 2440 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2696 2448 const char *sz = PyString_AS_STRING(val_use); 2697 2449 int nch = PyString_GET_SIZE(val_use); 2698 #else2699 if (!PyUnicode_Check(val)) {2700 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");2701 BREAK_FALSE;2702 }2703 if ((val_use = PyUnicode_AsUTF8String(val))==NULL)2704 BREAK_FALSE;2705 2706 const char *sz = PyBytes_AS_STRING(val_use);2707 int nch = PyBytes_GET_SIZE(val_use);2708 #endif2709 2450 2710 2451 *pp = (char *)nsMemory::Alloc(nch+1); … … 2724 2465 if (val == Py_None) 2725 2466 break; // Remains NULL. 2726 #if PY_MAJOR_VERSION <= 22727 2467 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2728 2468 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2731 2471 val_use = PyUnicode_FromObject(val); 2732 2472 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyUnicode_FromObject didnt return a Unicode object!"); 2733 #else2734 if (!PyUnicode_Check(val)) {2735 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");2736 BREAK_FALSE;2737 }2738 val_use = val;2739 Py_INCREF(val_use);2740 #endif2741 2473 if (PyUnicode_AsPRUnichar(val_use, pp, NULL) < 0) 2742 2474 BREAK_FALSE; … … 2793 2525 PRUint32 nch = 0; 2794 2526 if (val != Py_None) { 2795 #if PY_MAJOR_VERSION <= 22796 2527 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2797 2528 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2805 2536 sz = PyString_AS_STRING(val_use); 2806 2537 nch = PyString_GET_SIZE(val_use); 2807 #else2808 if (!PyUnicode_Check(val)) {2809 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");2810 BREAK_FALSE;2811 }2812 if ((val_use = PyUnicode_AsUTF8String(val))==NULL)2813 BREAK_FALSE;2814 2815 sz = PyBytes_AS_STRING(val_use);2816 nch = PyBytes_GET_SIZE(val_use);2817 #endif2818 2538 } 2819 2539 PRBool bBackFill = PR_FALSE; … … 2862 2582 2863 2583 if (val != Py_None) { 2864 #if PY_MAJOR_VERSION <= 22865 2584 if (!PyString_Check(val) && !PyUnicode_Check(val)) { 2866 2585 PyErr_SetString(PyExc_TypeError, "This parameter must be a string or Unicode object"); … … 2869 2588 val_use = PyUnicode_FromObject(val); 2870 2589 NS_ABORT_IF_FALSE(PyUnicode_Check(val_use), "PyUnicode_FromObject didnt return a Unicode object!"); 2871 #else2872 if (!PyUnicode_Check(val)) {2873 PyErr_SetString(PyExc_TypeError, "This parameter must be a unicode object");2874 BREAK_FALSE;2875 }2876 val_use = val;2877 Py_INCREF(val_use);2878 #endif2879 2590 if (PyUnicode_AsPRUnichar(val_use, &sz, &nch) < 0) 2880 2591 BREAK_FALSE; … … 3039 2750 // But the retval is often the last param described in the info. 3040 2751 if (!PySequence_Check(user_result) || 3041 #if PY_MAJOR_VERSION <= 23042 2752 PyString_Check(user_result) || 3043 #else3044 PyBytes_Check(user_result) ||3045 #endif3046 2753 PyUnicode_Check(user_result)) { 3047 2754 PyErr_SetString(PyExc_TypeError, "This function has multiple results, but a sequence was not given to fill them"); -
trunk/src/libs/xpcom18a4/python/src/dllmain.cpp
r59769 r59795 196 196 CEnterLeaveXPCOMFramework _celf; 197 197 PRInt32 cnt = PR_AtomicIncrement(&g_cLockCount); 198 if (cnt==1) { // First call 198 if (cnt==1) { // First call 199 199 if (!Py_IsInitialized()) { 200 200 Py_Initialize(); … … 204 204 if (PySys_GetObject((char*)"argv")==NULL) { 205 205 PyObject *path = PyList_New(0); 206 #if PY_MAJOR_VERSION <= 2207 206 PyObject *str = PyString_FromString(""); 208 #else209 PyObject *str = PyUnicode_FromString("");210 #endif211 207 PyList_Append(path, str); 212 208 PySys_SetObject((char*)"argv", path); … … 250 246 PR_DestroyLock(g_lockMain); 251 247 #ifndef PYXPCOM_USE_PYGILSTATE 252 // I can't locate a way to kill this - 248 // I can't locate a way to kill this - 253 249 // should I pass a dtor to PR_NewThreadPrivateIndex?? 254 250 // TlsFree(tlsIndex); … … 334 330 bHaveInitXPCOM = PR_TRUE; 335 331 // Register our custom interfaces. 336 332 337 333 Py_nsISupports::InitType(); 338 334 Py_nsIComponentManager::InitType(); … … 346 342 // for backward compatibility: 347 343 Py_nsIComponentManagerObsolete::InitType(); 348 344 349 345 } 350 346 return rc; -
trunk/src/libs/xpcom18a4/python/src/module/_xpcom.cpp
r59769 r59795 84 84 # endif 85 85 # ifdef VBOX_PYXPCOM_VERSIONED 86 # if PY_VERSION_HEX >= 0x03080000 && PY_VERSION_HEX < 0x03090000 87 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_8") 88 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_8) 89 90 # elif PY_VERSION_HEX >= 0x03070000 && PY_VERSION_HEX < 0x03080000 91 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_7") 92 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_7) 93 94 # elif PY_VERSION_HEX >= 0x03060000 && PY_VERSION_HEX < 0x03070000 95 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_6") 96 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_6) 97 98 # elif PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03060000 99 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_5") 100 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_5) 101 102 # elif PY_VERSION_HEX >= 0x03040000 && PY_VERSION_HEX < 0x03050000 103 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_4") 104 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_4) 105 106 # elif PY_VERSION_HEX >= 0x03030000 && PY_VERSION_HEX < 0x03040000 107 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_3") 108 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_3) 109 110 # elif PY_VERSION_HEX >= 0x03020000 && PY_VERSION_HEX < 0x03030000 111 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_2") 112 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_2) 113 114 # elif PY_VERSION_HEX >= 0x03010000 && PY_VERSION_HEX < 0x03020000 115 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython3_1") 116 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython3_1) 117 118 # elif PY_VERSION_HEX >= 0x02080000 && PY_VERSION_HEX < 0x02090000 86 # if PY_VERSION_HEX >= 0x02080000 119 87 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_8") 120 88 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_8) 121 89 122 # elif PY_VERSION_HEX >= 0x02070000 && PY_VERSION_HEX < 0x0208000090 # elif PY_VERSION_HEX >= 0x02070000 123 91 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_7") 124 92 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_7) 125 93 126 # elif PY_VERSION_HEX >= 0x02060000 && PY_VERSION_HEX < 0x0207000094 # elif PY_VERSION_HEX >= 0x02060000 127 95 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_6") 128 96 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_6) 97 98 # elif PY_VERSION_HEX >= 0x02050000 99 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_5") 100 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_5) 101 102 # elif PY_VERSION_HEX >= 0x02040000 103 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_4") 104 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_4) 105 106 # elif PY_VERSION_HEX >= 0x02030000 107 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython2_3") 108 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython2_3) 129 109 # else 130 # error "Fix module versioning. This Python version is not recognized."110 # error "Fix module versioning." 131 111 # endif 132 112 # else 133 113 # define MODULE_NAME MANGLE_MODULE_NAME("VBoxPython") 134 # if PY_MAJOR_VERSION <= 2 135 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython) 136 # else 137 # define initVBoxPython MANGLE_MODULE_INIT(PyInit_VBoxPython) 138 # endif 114 # define initVBoxPython MANGLE_MODULE_INIT(initVBoxPython) 139 115 # endif 140 116 #else … … 145 121 // interface support! 146 122 147 #ifndef VBOX148 123 /* deprecated, included for backward compatibility */ 149 124 static PyObject * … … 168 143 return Py_nsISupports::PyObjectFromInterface(ocm, NS_GET_IID(nsIComponentManagerObsolete), PR_FALSE); 169 144 } 170 #endif171 145 172 146 static PyObject * … … 221 195 } 222 196 223 #ifndef VBOX224 197 /* deprecated, included for backward compatibility */ 225 198 static PyObject * … … 231 204 return PyXPCOMMethod_GetComponentManager(self, args); 232 205 } 233 #endif234 206 235 207 static PyObject * … … 528 500 if (!PyArg_ParseTuple(args, "i", &bufSize)) 529 501 return NULL; 530 #if PY_MAJOR_VERSION <= 2531 502 return PyBuffer_New(bufSize); 532 #else533 return PyBytes_FromStringAndSize(NULL, bufSize);534 #endif535 503 } 536 504 … … 703 671 {"GetComponentManager", PyXPCOMMethod_GetComponentManager, 1}, 704 672 {"GetComponentRegistrar", PyXPCOMMethod_GetComponentRegistrar, 1}, 705 #ifndef VBOX706 673 {"NS_GetGlobalComponentManager", PyXPCOMMethod_NS_GetGlobalComponentManager, 1}, // deprecated 707 #endif708 674 {"XPTI_GetInterfaceInfoManager", PyXPCOMMethod_XPTI_GetInterfaceInfoManager, 1}, 709 675 {"XPTC_InvokeByIndex", PyXPCOMMethod_XPTC_InvokeByIndex, 1}, 710 676 {"GetServiceManager", PyXPCOMMethod_GetServiceManager, 1}, 711 #ifndef VBOX712 677 {"GetGlobalServiceManager", PyXPCOMMethod_GetGlobalServiceManager, 1}, // deprecated 713 678 {"IID", PyXPCOMMethod_IID, 1}, // IID is wrong - deprecated - not just IID, but CID, etc. 714 #endif715 679 {"ID", PyXPCOMMethod_IID, 1}, // This is the official name. 716 680 {"NS_ShutdownXPCOM", PyXPCOMMethod_NS_ShutdownXPCOM, 1}, … … 727 691 {"GetVariantValue", PyXPCOMMethod_GetVariantValue, 1}, 728 692 #ifdef VBOX 729 {"WaitForEvents", PyXPCOMMethod_WaitForEvents, 1},730 {"InterruptWait", PyXPCOMMethod_InterruptWait, 1},731 {"DeinitCOM", PyXPCOMMethod_DeinitCOM, 1},732 {"AttachThread", PyXPCOMMethod_AttachThread, 1},733 {"DetachThread", PyXPCOMMethod_DetachThread, 1},693 {"WaitForEvents", PyXPCOMMethod_WaitForEvents, 1}, 694 {"InterruptWait", PyXPCOMMethod_InterruptWait, 1}, 695 {"DeinitCOM", PyXPCOMMethod_DeinitCOM, 1}, 696 {"AttachThread", PyXPCOMMethod_AttachThread, 1}, 697 {"DetachThread", PyXPCOMMethod_DetachThread, 1}, 734 698 #endif 735 699 #ifdef VBOX_DEBUG_LIFETIMES … … 741 705 }; 742 706 743 #if PY_MAJOR_VERSION >= 3744 static struct PyModuleDef xpcom_module =745 {746 PyModuleDef_HEAD_INIT,747 MODULE_NAME, /* name of module */748 NULL, /* module documentation */749 -1, /* size of per-interpreter state or -1 if using globals */750 xpcom_methods751 };752 #endif753 754 755 707 #define REGISTER_IID(t) { \ 756 708 PyObject *iid_ob = Py_nsIID::PyObjectFromIID(NS_GET_IID(t)); \ … … 769 721 // The module init code. 770 722 // 771 #if PY_MAJOR_VERSION <= 2772 723 extern "C" NS_EXPORT 773 724 void 774 #else775 PyObject *776 #endif777 725 init_xpcom() { 778 726 PyObject *oModule; … … 780 728 // ensure the framework has valid state to work with. 781 729 if (!PyXPCOM_Globals_Ensure()) 782 #if PY_MAJOR_VERSION <= 2783 730 return; 784 #else785 return NULL;786 #endif787 731 788 732 // Must force Python to start using thread locks … … 790 734 791 735 // Create the module and add the functions 792 #if PY_MAJOR_VERSION <= 2793 736 oModule = Py_InitModule(MODULE_NAME, xpcom_methods); 794 #else795 oModule = PyModule_Create(&xpcom_module);796 #endif797 737 798 738 PyObject *dict = PyModule_GetDict(oModule); … … 801 741 { 802 742 PyErr_SetString(PyExc_MemoryError, "can't define error"); 803 #if PY_MAJOR_VERSION <= 2804 743 return; 805 #else806 return NULL;807 #endif808 744 } 809 745 PyDict_SetItemString(dict, "IIDType", (PyObject *)&Py_nsIID::type); … … 848 784 PyDict_SetItemString(dict, "NS_DEBUG", ob); 849 785 Py_DECREF(ob); 850 #if PY_MAJOR_VERSION >= 3851 return oModule;852 #endif853 786 } 854 787 … … 862 795 #include <iprt/stream.h> 863 796 864 #if PY_MAJOR_VERSION <= 2865 797 extern "C" NS_EXPORT 866 798 void 867 #else868 /** @todo r=klaus this is hacky, but as Python3 doesn't deal with ELF869 * visibility, assuming that all globals are visible (which is ugly and not870 * true in our case). */871 #undef PyMODINIT_FUNC872 #define PyMODINIT_FUNC extern "C" NS_EXPORT PyObject*873 PyMODINIT_FUNC874 #endif875 799 initVBoxPython() { /* NOTE! This name is redefined at the top of the file! */ 876 800 static bool s_vboxInited = false; … … 895 819 rc = com::Initialize(); 896 820 897 #if PY_MAJOR_VERSION <= 2898 821 init_xpcom(); 899 #else900 return init_xpcom();901 #endif902 822 } 903 #if PY_MAJOR_VERSION >= 3904 return NULL;905 #endif906 823 } 907 824 -
trunk/src/libs/xpcom18a4/python/test/test_test_component.py
r59769 r59795 253 253 test_attribute(c, "iid_value", component_iid, new_iid) 254 254 test_attribute(c, "iid_value", component_iid, str(new_iid), new_iid) 255 test_attribute(c, "iid_value", component_iid, xpcom._xpcom.I D(new_iid))255 test_attribute(c, "iid_value", component_iid, xpcom._xpcom.IID(new_iid)) 256 256 257 257 test_attribute_failure(c, "no_attribute", "boo", AttributeError) -
trunk/src/libs/xpcom18a4/python/vboxxpcom.py
r59769 r59795 1 1 """ 2 Copyright (C) 2008-201 6Oracle Corporation2 Copyright (C) 2008-2012 Oracle Corporation 3 3 4 4 This file is part of VirtualBox Open Source Edition (OSE), as … … 47 47 _oVBoxPythonMod = __import__(m) 48 48 break 49 except Exception asx:50 print ('m=%s x=%s' % (m, x))49 except Exception, x: 50 print 'm=%s x=%s' % (m, x); 51 51 #except: 52 52 # pass -
trunk/src/libs/xpcom18a4/python/xpt.py
r59769 r59795 72 72 import xpcom._xpcom 73 73 74 from .xpcom_consts import *74 from xpcom_consts import * 75 75 76 76 class Interface: … … 100 100 if xpcom.verbose: 101 101 # 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" 103 103 return Interface(xpcom._xpcom.IID_nsISupports) 104 104 105 105 def Describe_Python(self): 106 106 method_reprs = [] 107 methods = [m for m in self.methods if not m.IsNotXPCOM()]107 methods = filter(lambda m: not m.IsNotXPCOM(), self.methods) 108 108 for m in methods: 109 109 method_reprs.append(m.Describe_Python()) … … 130 130 s = s + ' Scriptable: ' + word + '\n' 131 131 s = s + ' Methods:\n' 132 methods = [m for m in self.methods if not m.IsNotXPCOM()]132 methods = filter(lambda m: not m.IsNotXPCOM(), self.methods) 133 133 if len(methods): 134 134 for m in methods: … … 153 153 except xpcom.Exception: 154 154 if xpcom.verbose: 155 print ("** GetMethodCount failed?? - assuming no methods")155 print "** GetMethodCount failed?? - assuming no methods" 156 156 self.items = [] 157 157 def __len__(self): … … 252 252 253 253 def desc(a): return a.Describe() 254 method_desc = string.join( list(map(desc, self.params)), ', ')254 method_desc = string.join(map(desc, self.params), ', ') 255 255 result_type = TypeDescriber(self.result_desc[0], None) 256 256 return_desc = result_type.Describe() … … 329 329 except xpcom.Exception: 330 330 if xpcom.verbose: 331 print ("** GetConstantCount failed?? - assuming no constants")331 print "** GetConstantCount failed?? - assuming no constants" 332 332 self.items = [] 333 333 def __len__(self): … … 452 452 describer_name = describer_name + "_" + mode.capitalize() 453 453 describer = getattr(interface, describer_name) 454 print (describer())454 print describer() 455 455 456 456 if __name__=='__main__': 457 457 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" 461 461 sys.argv.append('nsIInterfaceInfo') 462 462 sys.argv.append('-xptinfo')
Note:
See TracChangeset
for help on using the changeset viewer.

