VirtualBox

Ignore:
Timestamp:
Jun 10, 2013 4:31:35 PM (12 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
86321
Message:

libs/xpcom: touch up Java XPCOM wrapper generation, new common exception handlin
g model
Main/glue: Java glue code with better exception handling, indentation/coding style fixes both in the XSLT and the generated code, touched up Java sample code showing exception handling and getting all error information, Python indentation/whitespace cleanup
Main/idl: make more interfaces available over the webservice, some minor docs changes, whitespace cleanup
Main/webservice: redo error reporting through exceptions, no longer loses error
information, allow more fine-grained suppression of methods/attributed, touched up C++ webservice sample code to support showing the full error information, build system changes to prepare for incremental Java compilation, indentation fixesFrontends/VBoxShell: minor cleanups, coding style fixes, indentation fixes, elim
inate warnings

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r44649 r46478  
    22
    33"""
    4 Copyright (C) 2009-2012 Oracle Corporation
     4Copyright (C) 2009-2013 Oracle Corporation
    55
    66This file is part of VirtualBox Open Source Edition (OSE), as
     
    2626################################################################################
    2727
    28 import os,sys
     28import os, sys
    2929import traceback
    3030import shlex
     
    3333import platform
    3434from optparse import OptionParser
    35 
    36 g_batchmode = False
    37 g_scripfile = None
    38 g_cmd = None
    39 g_hasreadline = True
     35from pprint import pprint
     36
     37g_fBatchMode = False
     38g_sScriptFile = None
     39g_sCmd = None
     40g_fHasReadline = True
    4041try:
    41     if g_hasreadline:
    42         import readline
    43         import rlcompleter
    44 except:
    45     g_hasreadline = False
    46 
    47 
    48 g_prompt = "vbox> "
    49 
    50 g_hascolors = True
    51 term_colors = {
     42    import readline
     43    import rlcompleter
     44except ImportError:
     45    g_fHasReadline = False
     46
     47g_sPrompt = "vbox> "
     48
     49g_fHasColors = True
     50g_aTermColors = {
    5251    'red':'\033[31m',
    5352    'blue':'\033[94m',
     
    5756    'cyan':'\033[36m'
    5857    }
    59 def colored(string,color):
    60     if not g_hascolors:
    61         return string
    62     global term_colors
    63     col = term_colors.get(color,None)
     58def colored(strg, color):
     59    """
     60    Translates a string to one including coloring settings, if enabled.
     61    """
     62    if not g_fHasColors:
     63        return strg
     64    col = g_aTermColors.get(color, None)
    6465    if col:
    65         return col+str(string)+'\033[0m'
    66     else:
    67         return string
    68 
    69 if g_hasreadline:
    70   import string
    71   class CompleterNG(rlcompleter.Completer):
    72     def __init__(self, dic, ctx):
    73         self.ctx = ctx
    74         return rlcompleter.Completer.__init__(self,dic)
    75 
    76     def complete(self, text, state):
    77         """
    78         taken from:
    79         http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
    80         """
    81         if False and text == "":
    82             return ['\t',None][state]
    83         else:
    84             return rlcompleter.Completer.complete(self,text,state)
    85 
    86     def canBePath(self, phrase,word):
    87         return word.startswith('/')
    88 
    89     def canBeCommand(self, phrase, word):
    90         spaceIdx = phrase.find(" ")
    91         begIdx = readline.get_begidx()
    92         firstWord = (spaceIdx == -1 or begIdx < spaceIdx)
    93         if firstWord:
    94             return True
    95         if phrase.startswith('help'):
    96             return True
    97         return False
    98 
    99     def canBeMachine(self,phrase,word):
    100         return not self.canBePath(phrase,word) and not self.canBeCommand(phrase, word)
    101 
    102     def global_matches(self, text):
    103         """
    104         Compute matches when text is a simple name.
    105         Return a list of all names currently defined
    106         in self.namespace that match.
    107         """
    108 
    109         matches = []
    110         phrase = readline.get_line_buffer()
    111 
    112         try:
    113             if self.canBePath(phrase,text):
    114                 (dir,rest) = os.path.split(text)
    115                 n = len(rest)
    116                 for word in os.listdir(dir):
    117                     if n == 0 or word[:n] == rest:
    118                         matches.append(os.path.join(dir,word))
    119 
    120             if self.canBeCommand(phrase,text):
    121                 n = len(text)
    122                 for list in [ self.namespace ]:
    123                     for word in list:
    124                         if word[:n] == text:
     66        return col+str(strg)+'\033[0m'
     67    else:
     68        return strg
     69
     70if g_fHasReadline:
     71    class CompleterNG(rlcompleter.Completer):
     72        def __init__(self, dic, ctx):
     73            self.ctx = ctx
     74            rlcompleter.Completer.__init__(self, dic)
     75
     76        def complete(self, text, state):
     77            """
     78            taken from:
     79            http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
     80            """
     81            if False and text == "":
     82                return ['\t', None][state]
     83            else:
     84                return rlcompleter.Completer.complete(self, text, state)
     85
     86        def canBePath(self, _phrase, word):
     87            return word.startswith('/')
     88
     89        def canBeCommand(self, phrase, _word):
     90            spaceIdx = phrase.find(" ")
     91            begIdx = readline.get_begidx()
     92            firstWord = (spaceIdx == -1 or begIdx < spaceIdx)
     93            if firstWord:
     94                return True
     95            if phrase.startswith('help'):
     96                return True
     97            return False
     98
     99        def canBeMachine(self, phrase, word):
     100            return not self.canBePath(phrase, word) and not self.canBeCommand(phrase, word)
     101
     102        def global_matches(self, text):
     103            """
     104            Compute matches when text is a simple name.
     105            Return a list of all names currently defined
     106            in self.namespace that match.
     107            """
     108
     109            matches = []
     110            phrase = readline.get_line_buffer()
     111
     112            try:
     113                if self.canBePath(phrase, text):
     114                    (directory, rest) = os.path.split(text)
     115                    c = len(rest)
     116                    for word in os.listdir(directory):
     117                        if c == 0 or word[:c] == rest:
     118                            matches.append(os.path.join(directory, word))
     119
     120                if self.canBeCommand(phrase, text):
     121                    c = len(text)
     122                    for lst in [ self.namespace ]:
     123                        for word in lst:
     124                            if word[:c] == text:
     125                                matches.append(word)
     126
     127                if self.canBeMachine(phrase, text):
     128                    c = len(text)
     129                    for mach in getMachines(self.ctx, False, True):
     130                        # although it has autoconversion, we need to cast
     131                        # explicitly for subscripts to work
     132                        word = re.sub("(?<!\\\\) ", "\\ ", str(mach.name))
     133                        if word[:c] == text:
    125134                            matches.append(word)
    126 
    127             if self.canBeMachine(phrase,text):
    128                 n = len(text)
    129                 for m in getMachines(self.ctx, False, True):
    130                     # although it has autoconversion, we need to cast
    131                     # explicitly for subscripts to work
    132                     word = re.sub("(?<!\\\\) ", "\\ ", str(m.name))
    133                     if word[:n] == text:
    134                         matches.append(word)
    135                     word = str(m.id)
    136                     if word[:n] == text:
    137                         matches.append(word)
    138 
    139         except Exception,e:
    140             printErr(e)
    141             if g_verbose:
    142                 traceback.print_exc()
    143 
    144         return matches
    145 
    146 def autoCompletion(commands, ctx):
    147   if  not g_hasreadline:
    148       return
    149 
    150   comps = {}
    151   for (k,v) in commands.items():
    152       comps[k] = None
    153   completer = CompleterNG(comps, ctx)
    154   readline.set_completer(completer.complete)
    155   delims = readline.get_completer_delims()
    156   readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters
    157   readline.parse_and_bind("set editing-mode emacs")
    158   # OSX need it
    159   if platform.system() == 'Darwin':
    160       # see http://www.certif.com/spec_help/readline.html
    161       readline.parse_and_bind ("bind ^I rl_complete")
    162       readline.parse_and_bind ("bind ^W ed-delete-prev-word")
    163       # Doesn't work well
    164       # readline.parse_and_bind ("bind ^R em-inc-search-prev")
    165   readline.parse_and_bind("tab: complete")
    166 
    167 
    168 g_verbose = False
     135                        word = str(mach.id)
     136                        if word[:c] == text:
     137                            matches.append(word)
     138
     139            except Exception, e:
     140                printErr(self.ctx, e)
     141                if g_fVerbose:
     142                    traceback.print_exc()
     143
     144            return matches
     145
     146def autoCompletion(cmds, ctx):
     147    if not g_fHasReadline:
     148        return
     149
     150    comps = {}
     151    for (key, _value) in cmds.items():
     152        comps[key] = None
     153    completer = CompleterNG(comps, ctx)
     154    readline.set_completer(completer.complete)
     155    delims = readline.get_completer_delims()
     156    readline.set_completer_delims(re.sub("[\\./-]", "", delims)) # remove some of the delimiters
     157    readline.parse_and_bind("set editing-mode emacs")
     158    # OSX need it
     159    if platform.system() == 'Darwin':
     160        # see http://www.certif.com/spec_help/readline.html
     161        readline.parse_and_bind ("bind ^I rl_complete")
     162        readline.parse_and_bind ("bind ^W ed-delete-prev-word")
     163        # Doesn't work well
     164        # readline.parse_and_bind ("bind ^R em-inc-search-prev")
     165        readline.parse_and_bind("tab: complete")
     166
     167
     168g_fVerbose = False
    169169
    170170def split_no_quotes(s):
    171171    return shlex.split(s)
    172172
    173 def progressBar(ctx,p,wait=1000):
     173def progressBar(ctx, progress, wait=1000):
    174174    try:
    175         while not p.completed:
    176             print "%s %%\r" %(colored(str(p.percent),'red')),
     175        while not progress.completed:
     176            print "%s %%\r" % (colored(str(progress.percent), 'red')),
    177177            sys.stdout.flush()
    178             p.waitForCompletion(wait)
     178            progress.waitForCompletion(wait)
    179179            ctx['global'].waitForEvents(0)
    180         if int(p.resultCode) != 0:
    181             reportError(ctx, p)
     180        if int(progress.resultCode) != 0:
     181            reportError(ctx, progress)
    182182        return 1
    183183    except KeyboardInterrupt:
    184184        print "Interrupted."
    185185        ctx['interrupt'] = True
    186         if p.cancelable:
     186        if progress.cancelable:
    187187            print "Canceling task..."
    188             p.cancel()
    189         return 0
    190 
    191 def printErr(ctx,e):
    192      print colored(str(e), 'red')
    193 
    194 def reportError(ctx,progress):
    195     ei = progress.errorInfo
    196     if ei:
    197         print colored("Error in module '%s': %s" %(ei.component, ei.text), 'red')
    198 
    199 def colCat(ctx,str):
    200     return colored(str, 'magenta')
    201 
    202 def colVm(ctx,vm):
    203     return colored(vm, 'blue')
    204 
    205 def colPath(ctx,p):
    206     return colored(p, 'green')
    207 
    208 def colSize(ctx,m):
    209     return colored(m, 'red')
    210 
    211 def colPci(ctx,vm):
    212     return colored(vm, 'green')
    213 
    214 def colDev(ctx,vm):
    215     return colored(vm, 'cyan')
    216 
    217 def colSizeM(ctx,m):
    218     return colored(str(m)+'M', 'red')
    219 
    220 def createVm(ctx,name,kind):
    221     mgr = ctx['mgr']
    222     vb = ctx['vb']
    223     mach = vb.createMachine("", name, [], kind, "")
     188            progress.cancel()
     189        return 0
     190
     191def printErr(_ctx, e):
     192    print colored(str(e), 'red')
     193
     194def reportError(_ctx, progress):
     195    errorinfo = progress.errorInfo
     196    if errorinfo:
     197        print colored("Error in module '%s': %s" % (errorinfo.component, errorinfo.text), 'red')
     198
     199def colCat(_ctx, strg):
     200    return colored(strg, 'magenta')
     201
     202def colVm(_ctx, vmname):
     203    return colored(vmname, 'blue')
     204
     205def colPath(_ctx, path):
     206    return colored(path, 'green')
     207
     208def colSize(_ctx, byte):
     209    return colored(byte, 'red')
     210
     211def colPci(_ctx, pcidev):
     212    return colored(pcidev, 'green')
     213
     214def colDev(_ctx, pcidev):
     215    return colored(pcidev, 'cyan')
     216
     217def colSizeM(_ctx, mbyte):
     218    return colored(str(mbyte)+'M', 'red')
     219
     220def createVm(ctx, name, kind):
     221    vbox = ctx['vb']
     222    mach = vbox.createMachine("", name, [], kind, "")
    224223    mach.saveSettings()
    225     print "created machine with UUID",mach.id
    226     vb.registerMachine(mach)
     224    print "created machine with UUID", mach.id
     225    vbox.registerMachine(mach)
    227226    # update cache
    228227    getMachines(ctx, True)
    229228
    230 def removeVm(ctx,mach):
    231     mgr = ctx['mgr']
    232     vb = ctx['vb']
    233     id = mach.id
    234     print "removing machine ",mach.name,"with UUID",id
     229def removeVm(ctx, mach):
     230    uuid = mach.id
     231    print "removing machine ", mach.name, "with UUID", uuid
    235232    cmdClosedVm(ctx, mach, detachVmDevice, ["ALL"])
    236233    mach = mach.unregister(ctx['global'].constants.CleanupMode_Full)
    237234    if mach:
    238          mach.deleteSettings()
     235        mach.deleteSettings()
    239236    # update cache
    240237    getMachines(ctx, True)
    241238
    242 def startVm(ctx,mach,type):
     239def startVm(ctx, mach, vmtype):
    243240    mgr = ctx['mgr']
    244     vb = ctx['vb']
     241    vbox = ctx['vb']
    245242    perf = ctx['perf']
    246     session = mgr.getSessionObject(vb)
    247     progress = mach.launchVMProcess(session, type, "")
     243    session = mgr.getSessionObject(vbox)
     244    progress = mach.launchVMProcess(session, vmtype, "")
    248245    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
    249246        # we ignore exceptions to allow starting VM even if
    250247        # perf collector cannot be started
    251248        if perf:
    252           try:
    253             perf.setup(['*'], [mach], 10, 15)
    254           except Exception,e:
    255             printErr(ctx, e)
    256             if g_verbose:
    257                 traceback.print_exc()
     249            try:
     250                perf.setup(['*'], [mach], 10, 15)
     251            except Exception, e:
     252                printErr(ctx, e)
     253                if g_fVerbose:
     254                    traceback.print_exc()
    258255        session.unlockMachine()
    259256
    260257class CachedMach:
    261         def __init__(self, mach):
     258    def __init__(self, mach):
     259        if mach.accessible:
    262260            self.name = mach.name
    263             self.id = mach.id
    264 
    265 def cacheMachines(ctx,list):
     261        else:
     262            self.name = '<inaccessible>'
     263        self.id = mach.id
     264
     265def cacheMachines(_ctx, lst):
    266266    result = []
    267     for m in list:
    268         try:
    269             elem = CachedMach(m)
    270             result.append(elem)
    271         except:
    272             pass
     267    for mach in lst:
     268        elem = CachedMach(mach)
     269        result.append(elem)
    273270    return result
    274271
     
    277274        if ctx['_machlist'] is None or invalidate:
    278275            ctx['_machlist'] = ctx['global'].getArray(ctx['vb'], 'machines')
    279             ctx['_machlistsimple'] = cacheMachines(ctx,ctx['_machlist'])
     276            ctx['_machlistsimple'] = cacheMachines(ctx, ctx['_machlist'])
    280277        if simple:
    281278            return ctx['_machlistsimple']
     
    298295
    299296def getFacilityStatus(ctx, guest, facilityType):
    300     (status, ts) = guest.getFacilityStatus(facilityType)
     297    (status, _timestamp) = guest.getFacilityStatus(facilityType)
    301298    return asEnumElem(ctx, 'AdditionsFacilityStatus', status)
    302299       
     
    310307    exec cmds
    311308
    312 def printMouseEvent(ctx, mev):
    313     print "Mouse : absolute=%d x=%d y=%d z=%d buttons=%x" %(mev.absolute, mev.x, mev.y, mev.z, mev.buttons)
     309def printMouseEvent(_ctx, mev):
     310    print "Mouse : absolute=%d x=%d y=%d z=%d buttons=%x" % (mev.absolute, mev.x, mev.y, mev.z, mev.buttons)
    314311
    315312def printKbdEvent(ctx, kev):
    316313    print "Kbd: ", ctx['global'].getArray(kev, 'scancodes')
    317314
    318 def monitorSource(ctx, es, active, dur):
    319     def handleEventImpl(ev):
    320          type = ev.type
    321          print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType', type))
    322          if type == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:
    323              scev = ctx['global'].queryInterface(ev, 'IMachineStateChangedEvent')
    324              if scev:
    325                  print "machine state event: mach=%s state=%s" %(scev.machineId, scev.state)
    326          elif  type == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:
    327              gpcev = ctx['global'].queryInterface(ev, 'IGuestPropertyChangedEvent')
    328              if gpcev:
    329                  print "guest property change: name=%s value=%s" %(gpcev.name, gpcev.value)
    330          elif  type == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:
    331              psev = ctx['global'].queryInterface(ev, 'IMousePointerShapeChangedEvent')
    332              if psev:
    333                  shape = ctx['global'].getArray(psev, 'shape')
    334                  if shape is None:
    335                      print "pointer shape event - empty shape"
    336                  else:
    337                      print "pointer shape event: w=%d h=%d shape len=%d" %(psev.width, psev.height, len(shape))
    338          elif type == ctx['global'].constants.VBoxEventType_OnGuestMouse:
    339              mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')
    340              if mev:
    341                  printMouseEvent(ctx, mev)
    342          elif type == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
    343              kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')
    344              if kev:
    345                  printKbdEvent(ctx, kev)
     315def monitorSource(ctx, eventSource, active, dur):
     316    def handleEventImpl(event):
     317        evtype = event.type
     318        print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype))
     319        if evtype == ctx['global'].constants.VBoxEventType_OnMachineStateChanged:
     320            scev = ctx['global'].queryInterface(event, 'IMachineStateChangedEvent')
     321            if scev:
     322                print "machine state event: mach=%s state=%s" % (scev.machineId, scev.state)
     323        elif  evtype == ctx['global'].constants.VBoxEventType_OnGuestPropertyChanged:
     324            gpcev = ctx['global'].queryInterface(event, 'IGuestPropertyChangedEvent')
     325            if gpcev:
     326                print "guest property change: name=%s value=%s" % (gpcev.name, gpcev.value)
     327        elif  evtype == ctx['global'].constants.VBoxEventType_OnMousePointerShapeChanged:
     328            psev = ctx['global'].queryInterface(event, 'IMousePointerShapeChangedEvent')
     329            if psev:
     330                shape = ctx['global'].getArray(psev, 'shape')
     331                if shape is None:
     332                    print "pointer shape event - empty shape"
     333                else:
     334                    print "pointer shape event: w=%d h=%d shape len=%d" % (psev.width, psev.height, len(shape))
     335        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
     336            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
     337            if mev:
     338                printMouseEvent(ctx, mev)
     339        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
     340            kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent')
     341            if kev:
     342                printKbdEvent(ctx, kev)
    346343
    347344    class EventListener:
    348      def __init__(self, arg):
    349          pass
    350 
    351      def handleEvent(self, ev):
    352          try:
    353             # a bit convoluted QI to make it work with MS COM
    354             handleEventImpl(ctx['global'].queryInterface(ev, 'IEvent'))
    355          except:
    356             traceback.print_exc()
    357             pass
     345        def __init__(self, arg):
     346            pass
     347
     348        def handleEvent(self, event):
     349            try:
     350                # a bit convoluted QI to make it work with MS COM
     351                handleEventImpl(ctx['global'].queryInterface(event, 'IEvent'))
     352            except:
     353                traceback.print_exc()
     354            pass
    358355
    359356    if active:
    360357        listener = ctx['global'].createListener(EventListener)
    361358    else:
    362         listener = es.createListener()
     359        listener = eventSource.createListener()
    363360    registered = False
    364361    if dur == -1:
     
    366363        dur = 100000
    367364    try:
    368         es.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active)
     365        eventSource.registerListener(listener, [ctx['global'].constants.VBoxEventType_Any], active)
    369366        registered = True
    370367        end = time.time() + dur
     
    373370                ctx['global'].waitForEvents(500)
    374371            else:
    375                 ev = es.getEvent(listener, 500)
    376                 if ev:
    377                     handleEventImpl(ev)
     372                event = eventSource.getEvent(listener, 500)
     373                if event:
     374                    handleEventImpl(event)
    378375                    # otherwise waitable events will leak (active listeners ACK automatically)
    379                     es.eventProcessed(listener, ev)
     376                    eventSource.eventProcessed(listener, event)
    380377    # We need to catch all exceptions here, otherwise listener will never be unregistered
    381378    except:
     
    383380        pass
    384381    if listener and registered:
    385         es.unregisterListener(listener)
    386 
    387 
    388 tsLast = 0
    389 def recordDemo(ctx, console, file, dur):
    390     demo = open(file, 'w')
    391     header="VM="+console.machine.name+"\n"
     382        eventSource.unregisterListener(listener)
     383
     384
     385g_tsLast = 0
     386def recordDemo(ctx, console, filename, dur):
     387    demo = open(filename, 'w')
     388    header = "VM=" + console.machine.name + "\n"
    392389    demo.write(header)
    393390
    394     global tsLast
    395     tsLast = time.time()
     391    global g_tsLast
     392    g_tsLast = time.time()
    396393
    397394    def stamp():
    398         global tsLast
     395        global g_tsLast
    399396        tsCur = time.time()
    400         rv = int((tsCur-tsLast)*1000)
    401         tsLast = tsCur
    402         return rv
    403 
    404     def handleEventImpl(ev):
    405          type = ev.type
    406          #print "got event: %s %s" %(str(type), asEnumElem(ctx, 'VBoxEventType', type))
    407          if type == ctx['global'].constants.VBoxEventType_OnGuestMouse:
    408              mev = ctx['global'].queryInterface(ev, 'IGuestMouseEvent')
    409              if mev:
    410                  l = "%d: m %d %d %d %d %d %d\n" %(stamp(), mev.absolute, mev.x, mev.y, mev.z, mev.w, mev.buttons)
    411                  demo.write(l)
    412          elif type == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
    413              kev = ctx['global'].queryInterface(ev, 'IGuestKeyboardEvent')
    414              if kev:
    415                  l = "%d: k %s\n" %(stamp(), str(ctx['global'].getArray(kev, 'scancodes')))
    416                  demo.write(l)
     397        timePassed = int((tsCur-g_tsLast)*1000)
     398        g_tsLast = tsCur
     399        return timePassed
     400
     401    def handleEventImpl(event):
     402        evtype = event.type
     403        #print "got event: %s %s" % (str(evtype), asEnumElem(ctx, 'VBoxEventType', evtype))
     404        if evtype == ctx['global'].constants.VBoxEventType_OnGuestMouse:
     405            mev = ctx['global'].queryInterface(event, 'IGuestMouseEvent')
     406            if mev:
     407                line = "%d: m %d %d %d %d %d %d\n" % (stamp(), mev.absolute, mev.x, mev.y, mev.z, mev.w, mev.buttons)
     408                demo.write(line)
     409        elif evtype == ctx['global'].constants.VBoxEventType_OnGuestKeyboard:
     410            kev = ctx['global'].queryInterface(event, 'IGuestKeyboardEvent')
     411            if kev:
     412                line = "%d: k %s\n" % (stamp(), str(ctx['global'].getArray(kev, 'scancodes')))
     413                demo.write(line)
    417414
    418415    listener = console.eventSource.createListener()
     
    420417    # we create an aggregated event source to listen for multiple event sources (keyboard and mouse in our case)
    421418    agg = console.eventSource.createAggregator([console.keyboard.eventSource, console.mouse.eventSource])
    422     demo = open(file, 'w')
    423     header="VM="+console.machine.name+"\n"
     419    demo = open(filename, 'w')
     420    header = "VM=" + console.machine.name + "\n"
    424421    demo.write(header)
    425422    if dur == -1:
     
    431428        end = time.time() + dur
    432429        while  time.time() < end:
    433             ev = agg.getEvent(listener, 1000)
    434             if ev:
    435                 handleEventImpl(ev)
     430            event = agg.getEvent(listener, 1000)
     431            if event:
     432                handleEventImpl(event)
    436433                # keyboard/mouse events aren't waitable, so no need for eventProcessed
    437434    # We need to catch all exceptions here, otherwise listener will never be unregistered
     
    444441
    445442
    446 def playbackDemo(ctx, console, file, dur):
    447     demo = open(file, 'r')
     443def playbackDemo(ctx, console, filename, dur):
     444    demo = open(filename, 'r')
    448445
    449446    if dur == -1:
     
    465462            if time.time() > end:
    466463                break
    467             m = basere.search(line)
    468             if m is None:
     464            match = basere.search(line)
     465            if match is None:
    469466                continue
    470467
    471             dict = m.groupdict()
    472             stamp = dict['s']
    473             params = dict['p']
    474             type = dict['t']
     468            rdict = match.groupdict()
     469            stamp = rdict['s']
     470            params = rdict['p']
     471            rtype = rdict['t']
    475472
    476473            time.sleep(float(stamp)/1000)
    477474
    478             if type == 'k':
    479                 codes=kre.findall(params)
    480                 #print "KBD:",codes
     475            if rtype == 'k':
     476                codes = kre.findall(params)
     477                #print "KBD:", codes
    481478                kbd.putScancodes(codes)
    482             elif type == 'm':
     479            elif rtype == 'm':
    483480                mm = mre.search(params)
    484481                if mm is not None:
     
    486483                    if mdict['a'] == '1':
    487484                        # absolute
    488                         #print "MA: ",mdict['x'],mdict['y'],mdict['z'],mdict['b']
     485                        #print "MA: ", mdict['x'], mdict['y'], mdict['z'], mdict['b']
    489486                        mouse.putMouseEventAbsolute(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
    490487                    else:
    491                         #print "MR: ",mdict['x'],mdict['y'],mdict['b']
     488                        #print "MR: ", mdict['x'], mdict['y'], mdict['b']
    492489                        mouse.putMouseEvent(int(mdict['x']), int(mdict['y']), int(mdict['z']), int(mdict['w']), int(mdict['b']))
    493490
     
    501498
    502499
    503 def takeScreenshotOld(ctx,console,args):
     500def takeScreenshotOld(_ctx, console, args):
    504501    from PIL import Image
    505502    display = console.display
     
    512509    else:
    513510        screen = 0
    514     (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
     511    (fbw, fbh, _fbbpp) = display.getScreenResolution(screen)
    515512    if len(args) > 1:
    516513        w = int(args[1])
     
    522519        h = fbh
    523520
    524     print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
    525     data = display.takeScreenShotToArray(screen, w,h)
    526     size = (w,h)
     521    print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f)
     522    data = display.takeScreenShotToArray(screen, w, h)
     523    size = (w, h)
    527524    mode = "RGBA"
    528525    im = Image.frombuffer(mode, size, str(data), "raw", mode, 0, 1)
    529526    im.save(f, "PNG")
    530527
    531 def takeScreenshot(ctx,console,args):
     528def takeScreenshot(_ctx, console, args):
    532529    display = console.display
    533530    if len(args) > 0:
     
    539536    else:
    540537        screen = 0
    541     (fbw, fbh, fbbpp) = display.getScreenResolution(screen)
     538    (fbw, fbh, _fbbpp) = display.getScreenResolution(screen)
    542539    if len(args) > 1:
    543540        w = int(args[1])
     
    549546        h = fbh
    550547
    551     print "Saving screenshot (%d x %d) screen %d in %s..." %(w,h,screen,f)
    552     data = display.takeScreenShotPNGToArray(screen, w,h)
    553     size = (w,h)
    554     file = open(f, 'wb')
    555     file.write(data)
    556     file.close()
    557 
    558 def teleport(ctx,session,console,args):
     548    print "Saving screenshot (%d x %d) screen %d in %s..." % (w, h, screen, f)
     549    data = display.takeScreenShotPNGToArray(screen, w, h)
     550    pngfile = open(f, 'wb')
     551    pngfile.write(data)
     552    pngfile.close()
     553
     554def teleport(ctx, _session, console, args):
    559555    if args[0].find(":") == -1:
    560556        print "Use host:port format for teleport target"
    561557        return
    562     (host,port) = args[0].split(":")
     558    (host, port) = args[0].split(":")
    563559    if len(args) > 1:
    564560        passwd = args[1]
     
    567563
    568564    if len(args) > 2:
    569         maxDowntime  = int(args[2])
     565        maxDowntime = int(args[2])
    570566    else:
    571567        maxDowntime = 250
    572568
    573569    port = int(port)
    574     print "Teleporting to %s:%d..." %(host,port)
     570    print "Teleporting to %s:%d..." % (host, port)
    575571    progress = console.teleport(host, port, passwd, maxDowntime)
    576572    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
    577573        print "Success!"
    578574    else:
    579         reportError(ctx,progress)
    580 
    581 
    582 def guestStats(ctx,console,args):
     575        reportError(ctx, progress)
     576
     577
     578def guestStats(ctx, console, args):
    583579    guest = console.guest
    584580    # we need to set up guest statistics
     
    599595        try:
    600596            val = guest.getStatistic( cpu, all_stats[s])
    601             print "%s: %d" %(s, val)
     597            print "%s: %d" % (s, val)
    602598        except:
    603599            # likely not implemented
    604600            pass
    605601
    606 def plugCpu(ctx,machine,session,args):
     602def plugCpu(_ctx, machine, _session, args):
    607603    cpu = int(args[0])
    608     print "Adding CPU %d..." %(cpu)
     604    print "Adding CPU %d..." % (cpu)
    609605    machine.hotPlugCPU(cpu)
    610606
    611 def unplugCpu(ctx,machine,session,args):
     607def unplugCpu(_ctx, machine, _session, args):
    612608    cpu = int(args[0])
    613     print "Removing CPU %d..." %(cpu)
     609    print "Removing CPU %d..." % (cpu)
    614610    machine.hotUnplugCPU(cpu)
    615611
    616 def mountIso(ctx,machine,session,args):
     612def mountIso(_ctx, machine, _session, args):
    617613    machine.mountMedium(args[0], args[1], args[2], args[3], args[4])
    618614    machine.saveSettings()
    619615
    620 def cond(c,v1,v2):
     616def cond(c, v1, v2):
    621617    if c:
    622618        return v1
     
    624620        return v2
    625621
    626 def printHostUsbDev(ctx,ud):
    627     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))
    628 
    629 def printUsbDev(ctx,ud):
    630     print "  %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id,  colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)
    631 
    632 def printSf(ctx,sf):
    633     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"))
    634 
    635 def ginfo(ctx,console, args):
     622def printHostUsbDev(ctx, ud):
     623    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))
     624
     625def printUsbDev(_ctx, ud):
     626    print "  %s: %s (vendorId=%d productId=%d serial=%s)" % (ud.id,  colored(ud.product, 'blue'), ud.vendorId, ud.productId, ud.serialNumber)
     627
     628def printSf(ctx, sf):
     629    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"))
     630
     631def ginfo(ctx, console, _args):
    636632    guest = console.guest
    637633    if guest.additionsRunLevel != ctx['const'].AdditionsRunLevelType_None:
    638         print "Additions active, version %s"  %(guest.additionsVersion)
    639         print "Support seamless: %s"          %(getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless))
    640         print "Support graphics: %s"          %(getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics))
    641         print "Balloon size: %d"              %(guest.memoryBalloonSize)
    642         print "Statistic update interval: %d" %(guest.statisticsUpdateInterval)
     634        print "Additions active, version %s" % (guest.additionsVersion)
     635        print "Support seamless: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Seamless))
     636        print "Support graphics: %s" % (getFacilityStatus(ctx, guest, ctx['const'].AdditionsFacilityType_Graphics))
     637        print "Balloon size: %d" % (guest.memoryBalloonSize)
     638        print "Statistic update interval: %d" % (guest.statisticsUpdateInterval)
    643639    else:
    644640        print "No additions"
     
    646642    print "Attached USB:"
    647643    for ud in usbs:
    648          printUsbDev(ctx,ud)
     644        printUsbDev(ctx, ud)
    649645    rusbs = ctx['global'].getArray(console, 'remoteUSBDevices')
    650646    print "Remote USB:"
    651647    for ud in rusbs:
    652         printHostUsbDev(ctx,ud)
     648        printHostUsbDev(ctx, ud)
    653649    print "Transient shared folders:"
    654     sfs =  rusbs = ctx['global'].getArray(console, 'sharedFolders')
     650    sfs = rusbs = ctx['global'].getArray(console, 'sharedFolders')
    655651    for sf in sfs:
    656         printSf(ctx,sf)
    657 
    658 def cmdExistingVm(ctx,mach,cmd,args):
     652        printSf(ctx, sf)
     653
     654def cmdExistingVm(ctx, mach, cmd, args):
    659655    session = None
    660656    try:
    661         vb = ctx['vb']
    662         session = ctx['mgr'].getSessionObject(vb)
     657        vbox = ctx['vb']
     658        session = ctx['mgr'].getSessionObject(vbox)
    663659        mach.lockMachine(session, ctx['global'].constants.LockType_Shared)
    664     except Exception,e:
    665         printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
    666         if g_verbose:
     660    except Exception, e:
     661        printErr(ctx, "Session to '%s' not open: %s" % (mach.name, str(e)))
     662        if g_fVerbose:
    667663            traceback.print_exc()
    668664        return
    669665    if session.state != ctx['const'].SessionState_Locked:
    670         print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
     666        print "Session to '%s' in wrong state: %s" % (mach.name, session.state)
    671667        session.unlockMachine()
    672668        return
     
    677673        session.unlockMachine()
    678674        return
    679     console=session.console
    680     ops={'pause':           lambda: console.pause(),
    681          'resume':          lambda: console.resume(),
    682          'powerdown':       lambda: console.powerDown(),
    683          'powerbutton':     lambda: console.powerButton(),
    684          'stats':           lambda: perfStats(ctx, mach),
    685          'guest':           lambda: guestExec(ctx, mach, console, args),
    686          'ginfo':           lambda: ginfo(ctx, console, args),
    687          'guestlambda':     lambda: args[0](ctx, mach, console, args[1:]),
    688          'save':            lambda: progressBar(ctx,console.saveState()),
    689          'screenshot':      lambda: takeScreenshot(ctx,console,args),
    690          'teleport':        lambda: teleport(ctx,session,console,args),
    691          'gueststats':      lambda: guestStats(ctx, console, args),
    692          'plugcpu':         lambda: plugCpu(ctx, session.machine, session, args),
    693          'unplugcpu':       lambda: unplugCpu(ctx, session.machine, session, args),
    694          'mountiso':        lambda: mountIso(ctx, session.machine, session, args),
    695          }
     675    console = session.console
     676    ops = {'pause':           lambda: console.pause(),
     677           'resume':          lambda: console.resume(),
     678           'powerdown':       lambda: console.powerDown(),
     679           'powerbutton':     lambda: console.powerButton(),
     680           'stats':           lambda: perfStats(ctx, mach),
     681           'guest':           lambda: guestExec(ctx, mach, console, args),
     682           'ginfo':           lambda: ginfo(ctx, console, args),
     683           'guestlambda':     lambda: args[0](ctx, mach, console, args[1:]),
     684           'save':            lambda: progressBar(ctx, console.saveState()),
     685           'screenshot':      lambda: takeScreenshot(ctx, console, args),
     686           'teleport':        lambda: teleport(ctx, session, console, args),
     687           'gueststats':      lambda: guestStats(ctx, console, args),
     688           'plugcpu':         lambda: plugCpu(ctx, session.machine, session, args),
     689           'unplugcpu':       lambda: unplugCpu(ctx, session.machine, session, args),
     690           'mountiso':        lambda: mountIso(ctx, session.machine, session, args),
     691           }
    696692    try:
    697693        ops[cmd]()
     
    699695        ctx['interrupt'] = True
    700696    except Exception, e:
    701         printErr(ctx,e)
    702         if g_verbose:
     697        printErr(ctx, e)
     698        if g_fVerbose:
    703699            traceback.print_exc()
    704700
     
    706702
    707703
    708 def cmdClosedVm(ctx,mach,cmd,args=[],save=True):
     704def cmdClosedVm(ctx, mach, cmd, args=[], save=True):
    709705    session = ctx['global'].openMachineSession(mach, True)
    710706    mach = session.machine
     
    713709    except Exception, e:
    714710        save = False
    715         printErr(ctx,e)
    716         if g_verbose:
     711        printErr(ctx, e)
     712        if g_fVerbose:
    717713            traceback.print_exc()
    718714    if save:
     
    720716            mach.saveSettings()
    721717        except Exception, e:
    722             printErr(ctx,e)
    723             if g_verbose:
     718            printErr(ctx, e)
     719            if g_fVerbose:
    724720                traceback.print_exc()
    725721    ctx['global'].closeMachineSession(session)
    726722
    727723
    728 def cmdAnyVm(ctx,mach,cmd, args=[],save=False):
     724def cmdAnyVm(ctx, mach, cmd, args=[], save=False):
    729725    session = ctx['global'].openMachineSession(mach)
    730726    mach = session.machine
    731727    try:
    732          cmd(ctx, mach, session.console, args)
     728        cmd(ctx, mach, session.console, args)
    733729    except Exception, e:
    734         save = False;
    735         printErr(ctx,e)
    736         if g_verbose:
     730        save = False
     731        printErr(ctx, e)
     732        if g_fVerbose:
    737733            traceback.print_exc()
    738734    if save:
    739          mach.saveSettings()
     735        mach.saveSettings()
    740736    ctx['global'].closeMachineSession(session)
    741737
    742 def machById(ctx,id):
     738def machById(ctx, uuid):
    743739    try:
    744         mach = ctx['vb'].getMachine(id)
     740        mach = ctx['vb'].getMachine(uuid)
    745741    except:
    746         mach = ctx['vb'].findMachine(id)
     742        mach = ctx['vb'].findMachine(uuid)
    747743    return mach
    748744
    749745class XPathNode:
    750     def __init__(self, parent, obj, type):
     746    def __init__(self, parent, obj, ntype):
    751747        self.parent = parent
    752748        self.obj = obj
    753         self.type = type
     749        self.ntype = ntype
    754750    def lookup(self, subpath):
    755751        children = self.enum()
     
    761757    def enum(self):
    762758        return []
    763     def matches(self,subexp):
    764         if subexp == self.type:
     759    def matches(self, subexp):
     760        if subexp == self.ntype:
    765761            return True
    766         if not subexp.startswith(self.type):
     762        if not subexp.startswith(self.ntype):
    767763            return False
    768         m = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp)
     764        match = re.search(r"@(?P<a>\w+)=(?P<v>[^\'\[\]]+)", subexp)
    769765        matches = False
    770766        try:
    771             if m is not None:
    772                 dict = m.groupdict()
    773                 attr = dict['a']
    774                 val  = dict['v']
     767            if match is not None:
     768                xdict = match.groupdict()
     769                attr = xdict['a']
     770                val = xdict['v']
    775771                matches = (str(getattr(self.obj, attr)) == val)
    776772        except:
     
    778774        return matches
    779775    def apply(self, cmd):
    780         exec(cmd, {'obj':self.obj,'node':self,'ctx':self.getCtx()}, {})
     776        exec(cmd, {'obj':self.obj, 'node':self, 'ctx':self.getCtx()}, {})
    781777    def getCtx(self):
    782         if hasattr(self,'ctx'):
     778        if hasattr(self, 'ctx'):
    783779            return self.ctx
    784780        return self.parent.getCtx()
     
    792788    def enum(self):
    793789        children = []
    794         for n in self.getCtx()['global'].getArray(self.obj, self.attr):
    795             node = self.heldClass(self, n)
    796             children.append(node)
     790        for node in self.getCtx()['global'].getArray(self.obj, self.attr):
     791            nodexml = self.heldClass(self, node)
     792            children.append(nodexml)
    797793        return children
    798     def matches(self,subexp):
     794    def matches(self, subexp):
    799795        return subexp == self.xpathname
    800796
     
    803799        XPathNode.__init__(self, parent, obj, 'val '+xpathname)
    804800        self.xpathname = xpathname
    805     def matches(self,subexp):
     801    def matches(self, subexp):
    806802        return subexp == self.xpathname
    807803
     
    813809    def __init__(self, parent, obj):
    814810        XPathNode.__init__(self, parent, obj, 'vm')
    815     #def matches(self,subexp):
     811    #def matches(self, subexp):
    816812    #    return subexp=='vm'
    817813    def enum(self):
     
    834830    def __init__(self, parent, obj):
    835831        XPathNode.__init__(self, parent, obj, 'nic')
    836     def matches(self,subexp):
    837         return subexp=='nic'
     832    def matches(self, subexp):
     833        return subexp == 'nic'
    838834
    839835class XPathNodeRoot(XPathNode):
     
    843839    def enum(self):
    844840        return [XPathNodeHolderVM(self, self.ctx['vb'])]
    845     def matches(self,subexp):
     841    def matches(self, subexp):
    846842        return True
    847843
    848 def eval_xpath(ctx,scope):
     844def eval_xpath(ctx, scope):
    849845    pathnames = scope.split("/")[2:]
    850846    nodes = [XPathNodeRoot(ctx)]
    851     for p in pathnames:
     847    for path in pathnames:
    852848        seen = []
    853849        while len(nodes) > 0:
    854             n = nodes.pop()
    855             seen.append(n)
     850            node = nodes.pop()
     851            seen.append(node)
    856852        for s in seen:
    857             matches = s.lookup(p)
    858             for m in matches:
    859                 nodes.append(m)
     853            matches = s.lookup(path)
     854            for match in matches:
     855                nodes.append(match)
    860856        if len(nodes) == 0:
    861857            break
    862858    return nodes
    863859
    864 def argsToMach(ctx,args):
     860def argsToMach(ctx, args):
    865861    if len(args) < 2:
    866         print "usage: %s [vmname|uuid]" %(args[0])
     862        print "usage: %s [vmname|uuid]" % (args[0])
    867863        return None
    868     id = args[1]
    869     m = machById(ctx, id)
    870     if m == None:
    871         print "Machine '%s' is unknown, use list command to find available machines" %(id)
    872     return m
    873 
    874 def helpSingleCmd(cmd,h,sp):
     864    uuid = args[1]
     865    mach = machById(ctx, uuid)
     866    if mach == None:
     867        print "Machine '%s' is unknown, use list command to find available machines" % (uuid)
     868    return mach
     869
     870def helpSingleCmd(cmd, h, sp):
    875871    if sp != 0:
    876872        spec = " [ext from "+sp+"]"
    877873    else:
    878874        spec = ""
    879     print "    %s: %s%s" %(colored(cmd,'blue'),h,spec)
    880 
    881 def helpCmd(ctx, args):
     875    print "    %s: %s%s" % (colored(cmd, 'blue'), h, spec)
     876
     877def helpCmd(_ctx, args):
    882878    if len(args) == 1:
    883879        print "Help page:"
     
    890886        c = commands.get(cmd)
    891887        if c == None:
    892             print "Command '%s' not known" %(cmd)
     888            print "Command '%s' not known" % (cmd)
    893889        else:
    894890            helpSingleCmd(cmd, c[0], c[2])
    895891    return 0
    896892
    897 def asEnumElem(ctx,enum,elem):
    898     all = ctx['const'].all_values(enum)
    899     for e in all.keys():
    900         if str(elem) == str(all[e]):
     893def asEnumElem(ctx, enum, elem):
     894    enumVals = ctx['const'].all_values(enum)
     895    for e in enumVals.keys():
     896        if str(elem) == str(enumVals[e]):
    901897            return colored(e, 'green')
    902898    return colored("<unknown>", 'green')
    903899
    904 def enumFromString(ctx,enum,str):
    905     all = ctx['const'].all_values(enum)
    906     return all.get(str, None)
    907 
    908 def listCmd(ctx, args):
    909     for m in getMachines(ctx, True):
     900def enumFromString(ctx, enum, strg):
     901    enumVals = ctx['const'].all_values(enum)
     902    return enumVals.get(strg, None)
     903
     904def listCmd(ctx, _args):
     905    for mach in getMachines(ctx, True):
    910906        try:
    911             if m.teleporterEnabled:
     907            if mach.teleporterEnabled:
    912908                tele = "[T] "
    913909            else:
    914910                tele = "    "
    915                 print "%sMachine '%s' [%s], machineState=%s, sessionState=%s" %(tele,colVm(ctx,m.name),m.id,asEnumElem(ctx, "MachineState", m.state), asEnumElem(ctx,"SessionState", m.sessionState))
     911                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))
    916912        except Exception, e:
    917             printErr(ctx,e)
    918             if g_verbose:
     913            printErr(ctx, e)
     914            if g_fVerbose:
    919915                traceback.print_exc()
    920916    return 0
    921917
    922 def infoCmd(ctx,args):
     918def infoCmd(ctx, args):
    923919    if (len(args) < 2):
    924920        print "usage: info [vmname|uuid]"
    925921        return 0
    926     mach = argsToMach(ctx,args)
    927     if mach == None:
    928         return 0
    929     os = ctx['vb'].getGuestOSType(mach.OSTypeId)
     922    mach = argsToMach(ctx, args)
     923    if mach == None:
     924        return 0
     925    vmos = ctx['vb'].getGuestOSType(mach.OSTypeId)
    930926    print " One can use setvar <mach> <var> <value> to change variable, using name in []."
    931     print "  Name [name]: %s" %(colVm(ctx,mach.name))
    932     print "  Description [description]: %s" %(mach.description)
    933     print "  ID [n/a]: %s" %(mach.id)
    934     print "  OS Type [via OSTypeId]: %s" %(os.description)
    935     print "  Firmware [firmwareType]: %s (%s)" %(asEnumElem(ctx,"FirmwareType", mach.firmwareType),mach.firmwareType)
     927    print "  Name [name]: %s" % (colVm(ctx, mach.name))
     928    print "  Description [description]: %s" % (mach.description)
     929    print "  ID [n/a]: %s" % (mach.id)
     930    print "  OS Type [via OSTypeId]: %s" % (vmos.description)
     931    print "  Firmware [firmwareType]: %s (%s)" % (asEnumElem(ctx, "FirmwareType", mach.firmwareType), mach.firmwareType)
    936932    print
    937     print "  CPUs [CPUCount]: %d" %(mach.CPUCount)
    938     print "  RAM [memorySize]: %dM" %(mach.memorySize)
    939     print "  VRAM [VRAMSize]: %dM" %(mach.VRAMSize)
    940     print "  Monitors [monitorCount]: %d" %(mach.monitorCount)
    941     print "  Chipset [chipsetType]: %s (%s)" %(asEnumElem(ctx,"ChipsetType", mach.chipsetType), mach.chipsetType)
     933    print "  CPUs [CPUCount]: %d" % (mach.CPUCount)
     934    print "  RAM [memorySize]: %dM" % (mach.memorySize)
     935    print "  VRAM [VRAMSize]: %dM" % (mach.VRAMSize)
     936    print "  Monitors [monitorCount]: %d" % (mach.monitorCount)
     937    print "  Chipset [chipsetType]: %s (%s)" % (asEnumElem(ctx, "ChipsetType", mach.chipsetType), mach.chipsetType)
    942938    print
    943     print "  Clipboard mode [clipboardMode]: %s (%s)" %(asEnumElem(ctx,"ClipboardMode", mach.clipboardMode), mach.clipboardMode)
    944     print "  Machine status [n/a]: %s (%s)" % (asEnumElem(ctx,"SessionState", mach.sessionState), mach.sessionState)
     939    print "  Clipboard mode [clipboardMode]: %s (%s)" % (asEnumElem(ctx, "ClipboardMode", mach.clipboardMode), mach.clipboardMode)
     940    print "  Machine status [n/a]: %s (%s)" % (asEnumElem(ctx, "SessionState", mach.sessionState), mach.sessionState)
    945941    print
    946942    if mach.teleporterEnabled:
    947         print "  Teleport target on port %d (%s)" %(mach.teleporterPort, mach.teleporterPassword)
     943        print "  Teleport target on port %d (%s)" % (mach.teleporterPort, mach.teleporterPassword)
    948944        print
    949945    bios = mach.BIOSSettings
    950     print "  ACPI [BIOSSettings.ACPIEnabled]: %s" %(asState(bios.ACPIEnabled))
    951     print "  APIC [BIOSSettings.IOAPICEnabled]: %s" %(asState(bios.IOAPICEnabled))
     946    print "  ACPI [BIOSSettings.ACPIEnabled]: %s" % (asState(bios.ACPIEnabled))
     947    print "  APIC [BIOSSettings.IOAPICEnabled]: %s" % (asState(bios.IOAPICEnabled))
    952948    hwVirtEnabled = mach.getHWVirtExProperty(ctx['global'].constants.HWVirtExPropertyType_Enabled)
    953     print "  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled,value)]: " + asState(hwVirtEnabled)
     949    print "  Hardware virtualization [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_Enabled, value)]: " + asState(hwVirtEnabled)
    954950    hwVirtVPID = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_VPID)
    955     print "  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID,value)]: " + asState(hwVirtVPID)
     951    print "  VPID support [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_VPID, value)]: " + asState(hwVirtVPID)
    956952    hwVirtNestedPaging = mach.getHWVirtExProperty(ctx['const'].HWVirtExPropertyType_NestedPaging)
    957     print "  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging,value)]: " + asState(hwVirtNestedPaging)
     953    print "  Nested paging [guest win machine.setHWVirtExProperty(ctx[\\'const\\'].HWVirtExPropertyType_NestedPaging, value)]: " + asState(hwVirtNestedPaging)
    958954
    959955    print "  Hardware 3d acceleration [accelerate3DEnabled]: " + asState(mach.accelerate3DEnabled)
    960956    print "  Hardware 2d video acceleration [accelerate2DVideoEnabled]: " + asState(mach.accelerate2DVideoEnabled)
    961957
    962     print "  Use universal time [RTCUseUTC]: %s" %(asState(mach.RTCUseUTC))
    963     print "  HPET [HPETEnabled]: %s" %(asState(mach.HPETEnabled))
     958    print "  Use universal time [RTCUseUTC]: %s" % (asState(mach.RTCUseUTC))
     959    print "  HPET [HPETEnabled]: %s" % (asState(mach.HPETEnabled))
    964960    if mach.audioAdapter.enabled:
    965         print "  Audio [via audioAdapter]: chip %s; host driver %s" %(asEnumElem(ctx,"AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx,"AudioDriverType",  mach.audioAdapter.audioDriver))
     961        print "  Audio [via audioAdapter]: chip %s; host driver %s" % (asEnumElem(ctx, "AudioControllerType", mach.audioAdapter.audioController), asEnumElem(ctx, "AudioDriverType",  mach.audioAdapter.audioDriver))
    966962    if mach.USBController.enabled:
    967         print "  USB [via USBController]: high speed %s" %(asState(mach.USBController.enabledEHCI))
    968     print "  CPU hotplugging [CPUHotPlugEnabled]: %s" %(asState(mach.CPUHotPlugEnabled))
    969 
    970     print "  Keyboard [keyboardHIDType]: %s (%s)" %(asEnumElem(ctx,"KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType)
    971     print "  Pointing device [pointingHIDType]: %s (%s)" %(asEnumElem(ctx,"PointingHIDType", mach.pointingHIDType), mach.pointingHIDType)
     963        print "  USB [via USBController]: high speed %s" % (asState(mach.USBController.enabledEHCI))
     964    print "  CPU hotplugging [CPUHotPlugEnabled]: %s" % (asState(mach.CPUHotPlugEnabled))
     965
     966    print "  Keyboard [keyboardHIDType]: %s (%s)" % (asEnumElem(ctx, "KeyboardHIDType", mach.keyboardHIDType), mach.keyboardHIDType)
     967    print "  Pointing device [pointingHIDType]: %s (%s)" % (asEnumElem(ctx, "PointingHIDType", mach.pointingHIDType), mach.pointingHIDType)
    972968    print "  Last changed [n/a]: " + time.asctime(time.localtime(long(mach.lastStateChange)/1000))
    973969    # OSE has no VRDE
    974970    try:
    975         print "  VRDE server [VRDEServer.enabled]: %s" %(asState(mach.VRDEServer.enabled))
     971        print "  VRDE server [VRDEServer.enabled]: %s" % (asState(mach.VRDEServer.enabled))
    976972    except:
    977973        pass
    978974    print
    979     print colCat(ctx,"  I/O subsystem info:")
    980     print "   Cache enabled [IOCacheEnabled]: %s" %(asState(mach.IOCacheEnabled))
    981     print "   Cache size [IOCacheSize]: %dM" %(mach.IOCacheSize)
     975    print colCat(ctx, "  I/O subsystem info:")
     976    print "   Cache enabled [IOCacheEnabled]: %s" % (asState(mach.IOCacheEnabled))
     977    print "   Cache size [IOCacheSize]: %dM" % (mach.IOCacheSize)
    982978
    983979    controllers = ctx['global'].getArray(mach, 'storageControllers')
    984980    if controllers:
    985981        print
    986         print colCat(ctx,"  Controllers:")
     982        print colCat(ctx, "  Controllers:")
    987983    for controller in controllers:
    988         print "    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
     984        print "    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx, "StorageBus", controller.bus), asEnumElem(ctx, "StorageControllerType", controller.controllerType))
    989985
    990986    attaches = ctx['global'].getArray(mach, 'mediumAttachments')
    991987    if attaches:
    992988        print
    993         print colCat(ctx,"  Media:")
     989        print colCat(ctx, "  Media:")
    994990    for a in attaches:
    995         print "   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
    996         m = a.medium
     991        print "   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx, "DeviceType", a.type), a.type)
     992        medium = a.medium
    997993        if a.type == ctx['global'].constants.DeviceType_HardDisk:
    998994            print "   HDD:"
    999             print "    Id: %s" %(m.id)
    1000             print "    Location: %s" %(colPath(ctx,m.location))
    1001             print "    Name: %s"  %(m.name)
    1002             print "    Format: %s"  %(m.format)
     995            print "    Id: %s" % (medium.id)
     996            print "    Location: %s" % (colPath(ctx, medium.location))
     997            print "    Name: %s" % (medium.name)
     998            print "    Format: %s" % (medium.format)
    1003999
    10041000        if a.type == ctx['global'].constants.DeviceType_DVD:
    10051001            print "   DVD:"
    1006             if m:
    1007                 print "    Id: %s" %(m.id)
    1008                 print "    Name: %s" %(m.name)
    1009                 if m.hostDrive:
    1010                     print "    Host DVD %s" %(colPath(ctx,m.location))
     1002            if medium:
     1003                print "    Id: %s" % (medium.id)
     1004                print "    Name: %s" % (medium.name)
     1005                if medium.hostDrive:
     1006                    print "    Host DVD %s" % (colPath(ctx, medium.location))
    10111007                    if a.passthrough:
    1012                          print "    [passthrough mode]"
     1008                        print "    [passthrough mode]"
    10131009                else:
    1014                     print "    Virtual image at %s" %(colPath(ctx,m.location))
    1015                     print "    Size: %s" %(m.size)
     1010                    print "    Virtual image at %s" % (colPath(ctx, medium.location))
     1011                    print "    Size: %s" % (medium.size)
    10161012
    10171013        if a.type == ctx['global'].constants.DeviceType_Floppy:
    10181014            print "   Floppy:"
    1019             if m:
    1020                 print "    Id: %s" %(m.id)
    1021                 print "    Name: %s" %(m.name)
    1022                 if m.hostDrive:
    1023                     print "    Host floppy %s" %(colPath(ctx,m.location))
     1015            if medium:
     1016                print "    Id: %s" % (medium.id)
     1017                print "    Name: %s" % (medium.name)
     1018                if medium.hostDrive:
     1019                    print "    Host floppy %s" % (colPath(ctx, medium.location))
    10241020                else:
    1025                     print "    Virtual image at %s" %(colPath(ctx,m.location))
    1026                     print "    Size: %s" %(m.size)
     1021                    print "    Virtual image at %s" % (colPath(ctx, medium.location))
     1022                    print "    Size: %s" % (medium.size)
    10271023
    10281024    print
    1029     print colCat(ctx,"  Shared folders:")
     1025    print colCat(ctx, "  Shared folders:")
    10301026    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
    1031         printSf(ctx,sf)
     1027        printSf(ctx, sf)
    10321028
    10331029    return 0
     
    10371033        print "usage: start name <frontend>"
    10381034        return 0
    1039     mach = argsToMach(ctx,args)
     1035    mach = argsToMach(ctx, args)
    10401036    if mach == None:
    10411037        return 0
    10421038    if len(args) > 2:
    1043         type = args[2]
    1044     else:
    1045         type = "gui"
    1046     startVm(ctx, mach, type)
     1039        vmtype = args[2]
     1040    else:
     1041        vmtype = "gui"
     1042    startVm(ctx, mach, vmtype)
    10471043    return 0
    10481044
     
    10541050    oskind = args[2]
    10551051    try:
    1056          ctx['vb'].getGuestOSType(oskind)
    1057     except Exception, e:
    1058         print 'Unknown OS type:',oskind
     1052        ctx['vb'].getGuestOSType(oskind)
     1053    except Exception:
     1054        print 'Unknown OS type:', oskind
    10591055        return 0
    10601056    createVm(ctx, name, oskind)
    10611057    return 0
    10621058
    1063 def ginfoCmd(ctx,args):
     1059def ginfoCmd(ctx, args):
    10641060    if (len(args) < 2):
    10651061        print "usage: ginfo [vmname|uuid]"
    10661062        return 0
    1067     mach = argsToMach(ctx,args)
     1063    mach = argsToMach(ctx, args)
    10681064    if mach == None:
    10691065        return 0
     
    10711067    return 0
    10721068
    1073 def execInGuest(ctx,console,args,env,user,passwd,tmo,inputPipe=None,outputPipe=None):
     1069def execInGuest(ctx, console, args, env, user, passwd, tmo, inputPipe=None, outputPipe=None):
    10741070    if len(args) < 1:
    10751071        print "exec in guest needs at least program name"
     
    10791075    # shall contain program name as argv[0]
    10801076    gargs = args
    1081     print "executing %s with args %s as %s" %(args[0], gargs, user)
     1077    print "executing %s with args %s as %s" % (args[0], gargs, user)
    10821078    flags = 0
    10831079    if inputPipe is not None:
     
    10851081    print args[0]
    10861082    process = guestSession.processCreate(args[0], gargs, env, [], tmo)
    1087     print "executed with pid %d" %(process.PID)
     1083    print "executed with pid %d" % (process.PID)
    10881084    if pid != 0:
    10891085        try:
     
    11131109                if data and len(data) > 0:
    11141110                    if outputPipe is not None:
    1115                         outputPipe(ctx,data)
     1111                        outputPipe(ctx, data)
    11161112                    else:
    11171113                        sys.stdout.write(data)
     
    11251121            if progress.cancelable:
    11261122                progress.cancel()
    1127         (reason, code, flags) = guest.getProcessStatus(pid)
    1128         print "Exit code: %d" %(code)
     1123        (_reason, code, _flags) = guest.getProcessStatus(pid)
     1124        print "Exit code: %d" % (code)
    11291125        return 0
    11301126    else:
    11311127        reportError(ctx, progress)
    11321128
    1133 def copyToGuest(ctx,console,args,user,passwd):
     1129def copyToGuest(ctx, console, args, user, passwd):
    11341130    src = args[0]
    11351131    dst = args[1]
    11361132    flags = 0
    1137     print "Copying host %s to guest %s" %(src,dst)
     1133    print "Copying host %s to guest %s" % (src, dst)
    11381134    progress = console.guest.copyToGuest(src, dst, user, passwd, flags)
    11391135    progressBar(ctx, progress)
     
    11521148
    11531149
    1154 def getCred(ctx):
     1150def getCred(_ctx):
    11551151    import getpass
    11561152    user = getpass.getuser()
    1157     user_inp = nh_raw_input("User (%s): " %(user))
     1153    user_inp = nh_raw_input("User (%s): " % (user))
    11581154    if len (user_inp) > 0:
    11591155        user = user_inp
    11601156    passwd = getpass.getpass()
    11611157
    1162     return (user,passwd)
    1163 
    1164 def gexecCmd(ctx,args):
     1158    return (user, passwd)
     1159
     1160def gexecCmd(ctx, args):
    11651161    if (len(args) < 2):
    11661162        print "usage: gexec [vmname|uuid] command args"
    11671163        return 0
    1168     mach = argsToMach(ctx,args)
     1164    mach = argsToMach(ctx, args)
    11691165    if mach == None:
    11701166        return 0
    11711167    gargs = args[2:]
    11721168    env = [] # ["DISPLAY=:0"]
    1173     (user,passwd) = getCred(ctx)
    1174     gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd,10000))
     1169    (user, passwd) = getCred(ctx)
     1170    gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000))
    11751171    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    11761172    return 0
    11771173
    1178 def gcopyCmd(ctx,args):
     1174def gcopyCmd(ctx, args):
    11791175    if (len(args) < 2):
    11801176        print "usage: gcopy [vmname|uuid] host_path guest_path"
    11811177        return 0
    1182     mach = argsToMach(ctx,args)
     1178    mach = argsToMach(ctx, args)
    11831179    if mach == None:
    11841180        return 0
    11851181    gargs = args[2:]
    1186     (user,passwd) = getCred(ctx)
    1187     gargs.insert(0, lambda ctx,mach,console,args: copyToGuest(ctx,console,args,user,passwd))
     1182    (user, passwd) = getCred(ctx)
     1183    gargs.insert(0, lambda ctx, mach, console, args: copyToGuest(ctx, console, args, user, passwd))
    11881184    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    11891185    return 0
    11901186
    1191 def readCmdPipe(ctx,hcmd):
     1187def readCmdPipe(ctx, _hcmd):
    11921188    try:
    11931189        return ctx['process'].communicate()[0]
     
    11951191        return None
    11961192
    1197 def gpipeCmd(ctx,args):
     1193def gpipeCmd(ctx, args):
    11981194    if (len(args) < 4):
    11991195        print "usage: gpipe [vmname|uuid] hostProgram guestProgram, such as gpipe linux  '/bin/uname -a' '/bin/sh -c \"/usr/bin/tee; /bin/uname -a\"'"
    12001196        return 0
    1201     mach = argsToMach(ctx,args)
     1197    mach = argsToMach(ctx, args)
    12021198    if mach == None:
    12031199        return 0
    12041200    hcmd = args[2]
    12051201    gcmd = args[3]
    1206     (user,passwd) = getCred(ctx)
     1202    (user, passwd) = getCred(ctx)
    12071203    import subprocess
    12081204    ctx['process'] = subprocess.Popen(split_no_quotes(hcmd), stdout=subprocess.PIPE)
    12091205    gargs = split_no_quotes(gcmd)
    12101206    env = []
    1211     gargs.insert(0, lambda ctx,mach,console,args: execInGuest(ctx,console,args,env,user,passwd, 10000,lambda ctx:readCmdPipe(ctx, hcmd)))
     1207    gargs.insert(0, lambda ctx, mach, console, args: execInGuest(ctx, console, args, env, user, passwd, 10000, lambda ctx:readCmdPipe(ctx, hcmd)))
    12121208    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    12131209    try:
     
    12201216
    12211217def removeVmCmd(ctx, args):
    1222     mach = argsToMach(ctx,args)
     1218    mach = argsToMach(ctx, args)
    12231219    if mach == None:
    12241220        return 0
     
    12271223
    12281224def pauseCmd(ctx, args):
    1229     mach = argsToMach(ctx,args)
     1225    mach = argsToMach(ctx, args)
    12301226    if mach == None:
    12311227        return 0
     
    12341230
    12351231def powerdownCmd(ctx, args):
    1236     mach = argsToMach(ctx,args)
     1232    mach = argsToMach(ctx, args)
    12371233    if mach == None:
    12381234        return 0
     
    12411237
    12421238def powerbuttonCmd(ctx, args):
    1243     mach = argsToMach(ctx,args)
     1239    mach = argsToMach(ctx, args)
    12441240    if mach == None:
    12451241        return 0
     
    12481244
    12491245def resumeCmd(ctx, args):
    1250     mach = argsToMach(ctx,args)
     1246    mach = argsToMach(ctx, args)
    12511247    if mach == None:
    12521248        return 0
     
    12551251
    12561252def saveCmd(ctx, args):
    1257     mach = argsToMach(ctx,args)
     1253    mach = argsToMach(ctx, args)
    12581254    if mach == None:
    12591255        return 0
     
    12621258
    12631259def statsCmd(ctx, args):
    1264     mach = argsToMach(ctx,args)
     1260    mach = argsToMach(ctx, args)
    12651261    if mach == None:
    12661262        return 0
     
    12721268        print "usage: guest name commands"
    12731269        return 0
    1274     mach = argsToMach(ctx,args)
     1270    mach = argsToMach(ctx, args)
    12751271    if mach == None:
    12761272        return 0
     
    12851281        print "usage: screenshot vm <file> <width> <height> <monitor>"
    12861282        return 0
    1287     mach = argsToMach(ctx,args)
     1283    mach = argsToMach(ctx, args)
    12881284    if mach == None:
    12891285        return 0
     
    12951291        print "usage: teleport name host:port <password>"
    12961292        return 0
    1297     mach = argsToMach(ctx,args)
     1293    mach = argsToMach(ctx, args)
    12981294    if mach == None:
    12991295        return 0
     
    13011297    return 0
    13021298
    1303 def portalsettings(ctx,mach,args):
     1299def portalsettings(_ctx, mach, args):
    13041300    enabled = args[0]
    13051301    mach.teleporterEnabled = enabled
     
    13141310        print "usage: openportal name port <password>"
    13151311        return 0
    1316     mach = argsToMach(ctx,args)
     1312    mach = argsToMach(ctx, args)
    13171313    if mach == None:
    13181314        return 0
     
    13311327        print "usage: closeportal name"
    13321328        return 0
    1333     mach = argsToMach(ctx,args)
     1329    mach = argsToMach(ctx, args)
    13341330    if mach == None:
    13351331        return 0
     
    13421338        print "usage: gueststats name <check interval>"
    13431339        return 0
    1344     mach = argsToMach(ctx,args)
     1340    mach = argsToMach(ctx, args)
    13451341    if mach == None:
    13461342        return 0
     
    13481344    return 0
    13491345
    1350 def plugcpu(ctx,mach,args):
     1346def plugcpu(_ctx, mach, args):
    13511347    plug = args[0]
    13521348    cpu = args[1]
    13531349    if plug:
    1354         print "Adding CPU %d..." %(cpu)
     1350        print "Adding CPU %d..." % (cpu)
    13551351        mach.hotPlugCPU(cpu)
    13561352    else:
    1357         print "Removing CPU %d..." %(cpu)
     1353        print "Removing CPU %d..." % (cpu)
    13581354        mach.hotUnplugCPU(cpu)
    13591355
     
    13621358        print "usage: plugcpu name cpuid"
    13631359        return 0
    1364     mach = argsToMach(ctx,args)
     1360    mach = argsToMach(ctx, args)
    13651361    if mach == None:
    13661362        return 0
     
    13761372        print "usage: unplugcpu name cpuid"
    13771373        return 0
    1378     mach = argsToMach(ctx,args)
     1374    mach = argsToMach(ctx, args)
    13791375    if mach == None:
    13801376        return 0
     
    13861382    return 0
    13871383
    1388 def setvar(ctx,mach,args):
     1384def setvar(_ctx, _mach, args):
    13891385    expr = 'mach.'+args[0]+' = '+args[1]
    1390     print "Executing",expr
     1386    print "Executing", expr
    13911387    exec expr
    13921388
     
    13951391        print "usage: setvar [vmname|uuid] expr value"
    13961392        return 0
    1397     mach = argsToMach(ctx,args)
     1393    mach = argsToMach(ctx, args)
    13981394    if mach == None:
    13991395        return 0
     
    14011397    return 0
    14021398
    1403 def setvmextra(ctx,mach,args):
     1399def setvmextra(_ctx, mach, args):
    14041400    key = args[0]
    14051401    value = args[1]
    1406     print "%s: setting %s to %s" %(mach.name, key, value)
     1402    print "%s: setting %s to %s" % (mach.name, key, value)
    14071403    mach.setExtraData(key, value)
    14081404
     
    14201416        return 0
    14211417
    1422     mach = argsToMach(ctx,args)
     1418    mach = argsToMach(ctx, args)
    14231419    if mach == None:
    14241420        return 0
     
    14271423
    14281424def printExtraKey(obj, key, value):
    1429     print "%s: '%s' = '%s'" %(obj, key, value)
     1425    print "%s: '%s' = '%s'" % (obj, key, value)
    14301426
    14311427def getExtraDataCmd(ctx, args):
     
    14411437        obj = ctx['vb']
    14421438    else:
    1443         obj = argsToMach(ctx,args)
     1439        obj = argsToMach(ctx, args)
    14441440        if obj == None:
    14451441            return 0
     
    14541450    return 0
    14551451
    1456 def quitCmd(ctx, args):
     1452def quitCmd(_ctx, _args):
    14571453    return 1
    14581454
     
    14621458        return 0
    14631459
    1464     for (k,v) in aliases.items():
    1465         print "'%s' is an alias for '%s'" %(k,v)
     1460    for (key, value) in aliases.items():
     1461        print "'%s' is an alias for '%s'" % (key, value)
    14661462    return 0
    14671463
    14681464def verboseCmd(ctx, args):
    1469     global g_verbose
     1465    global g_fVerbose
    14701466    if (len(args) > 1):
    1471         g_verbose = (args[1]=='on')
    1472     else:
    1473         g_verbose = not g_verbose
     1467        g_fVerbose = (args[1]=='on')
     1468    else:
     1469        g_fVerbose = not g_fVerbose
    14741470    return 0
    14751471
    14761472def colorsCmd(ctx, args):
    1477     global g_hascolors
     1473    global g_fHasColors
    14781474    if (len(args) > 1):
    1479         g_hascolors = (args[1]=='on')
    1480     else:
    1481         g_hascolors = not g_hascolors
     1475        g_fHasColors = (args[1] == 'on')
     1476    else:
     1477        g_fHasColors = not g_fHasColors
    14821478    return 0
    14831479
    14841480def hostCmd(ctx, args):
    1485    vb = ctx['vb']
    1486    print "VirtualBox version %s" %(colored(vb.version, 'blue'))
    1487    props = vb.systemProperties
    1488    print "Machines: %s" %(colPath(ctx,props.defaultMachineFolder))
    1489 
    1490    #print "Global shared folders:"
    1491    #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
    1492    #    printSf(ctx,sf)
    1493    host = vb.host
    1494    cnt = host.processorCount
    1495    print colCat(ctx,"Processors:")
    1496    print "  available/online: %d/%d " %(cnt,host.processorOnlineCount)
    1497    for i in range(0,cnt):
    1498        print "  processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
    1499 
    1500    print colCat(ctx, "RAM:")
    1501    print "  %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
    1502    print colCat(ctx,"OS:");
    1503    print "  %s (%s)" %(host.operatingSystem, host.OSVersion)
    1504    if host.acceleration3DAvailable:
    1505        print colCat(ctx,"3D acceleration available")
    1506    else:
    1507        print colCat(ctx,"3D acceleration NOT available")
    1508 
    1509    print colCat(ctx,"Network interfaces:")
    1510    for ni in ctx['global'].getArray(host, 'networkInterfaces'):
    1511        print "  %s (%s)" %(ni.name, ni.IPAddress)
    1512 
    1513    print colCat(ctx,"DVD drives:")
    1514    for dd in ctx['global'].getArray(host, 'DVDDrives'):
    1515        print "  %s - %s" %(dd.name, dd.description)
    1516 
    1517    print colCat(ctx,"Floppy drives:")
    1518    for dd in ctx['global'].getArray(host, 'floppyDrives'):
    1519        print "  %s - %s" %(dd.name, dd.description)
    1520 
    1521    print colCat(ctx,"USB devices:")
    1522    for ud in ctx['global'].getArray(host, 'USBDevices'):
    1523        printHostUsbDev(ctx,ud)
    1524 
    1525    if ctx['perf']:
    1526      for metric in ctx['perf'].query(["*"], [host]):
    1527        print metric['name'], metric['values_as_string']
    1528 
    1529    return 0
     1481    vbox = ctx['vb']
     1482    try:
     1483        print "VirtualBox version %s" % (colored(vbox.version, 'blue'))
     1484    except Exception, e:
     1485        printErr(ctx, e)
     1486        if g_fVerbose:
     1487            traceback.print_exc()
     1488    props = vbox.systemProperties
     1489    print "Machines: %s" % (colPath(ctx, props.defaultMachineFolder))
     1490
     1491    #print "Global shared folders:"
     1492    #for ud in ctx['global'].getArray(vbox, 'sharedFolders'):
     1493    #    printSf(ctx, sf)
     1494    host = vbox.host
     1495    cnt = host.processorCount
     1496    print colCat(ctx, "Processors:")
     1497    print "  available/online: %d/%d " % (cnt, host.processorOnlineCount)
     1498    for i in range(0, cnt):
     1499        print "  processor #%d speed: %dMHz %s" % (i, host.getProcessorSpeed(i), host.getProcessorDescription(i))
     1500
     1501    print colCat(ctx, "RAM:")
     1502    print "  %dM (free %dM)" % (host.memorySize, host.memoryAvailable)
     1503    print colCat(ctx, "OS:")
     1504    print "  %s (%s)" % (host.operatingSystem, host.OSVersion)
     1505    if host.acceleration3DAvailable:
     1506        print colCat(ctx, "3D acceleration available")
     1507    else:
     1508        print colCat(ctx, "3D acceleration NOT available")
     1509
     1510    print colCat(ctx, "Network interfaces:")
     1511    for ni in ctx['global'].getArray(host, 'networkInterfaces'):
     1512        print "  %s (%s)" % (ni.name, ni.IPAddress)
     1513
     1514    print colCat(ctx, "DVD drives:")
     1515    for dd in ctx['global'].getArray(host, 'DVDDrives'):
     1516        print "  %s - %s" % (dd.name, dd.description)
     1517
     1518    print colCat(ctx, "Floppy drives:")
     1519    for dd in ctx['global'].getArray(host, 'floppyDrives'):
     1520        print "  %s - %s" % (dd.name, dd.description)
     1521
     1522    print colCat(ctx, "USB devices:")
     1523    for ud in ctx['global'].getArray(host, 'USBDevices'):
     1524        printHostUsbDev(ctx, ud)
     1525
     1526    if ctx['perf']:
     1527        for metric in ctx['perf'].query(["*"], [host]):
     1528            print metric['name'], metric['values_as_string']
     1529
     1530    return 0
    15301531
    15311532def monitorGuestCmd(ctx, args):
     
    15331534        print "usage: monitorGuest name (duration)"
    15341535        return 0
    1535     mach = argsToMach(ctx,args)
     1536    mach = argsToMach(ctx, args)
    15361537    if mach == None:
    15371538        return 0
     
    15401541        dur = float(args[2])
    15411542    active = False
    1542     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  monitorSource(ctx, console.eventSource, active, dur)])
     1543    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.eventSource, active, dur)])
    15431544    return 0
    15441545
     
    15471548        print "usage: monitorGuestKbd name (duration)"
    15481549        return 0
    1549     mach = argsToMach(ctx,args)
     1550    mach = argsToMach(ctx, args)
    15501551    if mach == None:
    15511552        return 0
     
    15541555        dur = float(args[2])
    15551556    active = False
    1556     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  monitorSource(ctx, console.keyboard.eventSource, active, dur)])
     1557    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.keyboard.eventSource, active, dur)])
    15571558    return 0
    15581559
     
    15611562        print "usage: monitorGuestMouse name (duration)"
    15621563        return 0
    1563     mach = argsToMach(ctx,args)
     1564    mach = argsToMach(ctx, args)
    15641565    if mach == None:
    15651566        return 0
     
    15681569        dur = float(args[2])
    15691570    active = False
    1570     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  monitorSource(ctx, console.mouse.eventSource, active, dur)])
     1571    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  monitorSource(ctx, console.mouse.eventSource, active, dur)])
    15711572    return 0
    15721573
     
    15831584    return 0
    15841585
    1585 def getAdapterType(ctx, type):
    1586     if (type == ctx['global'].constants.NetworkAdapterType_Am79C970A or
    1587         type == ctx['global'].constants.NetworkAdapterType_Am79C973):
     1586def getAdapterType(ctx, natype):
     1587    if (natype == ctx['global'].constants.NetworkAdapterType_Am79C970A or
     1588        natype == ctx['global'].constants.NetworkAdapterType_Am79C973):
    15881589        return "pcnet"
    1589     elif (type == ctx['global'].constants.NetworkAdapterType_I82540EM or
    1590           type == ctx['global'].constants.NetworkAdapterType_I82545EM or
    1591           type == ctx['global'].constants.NetworkAdapterType_I82543GC):
     1590    elif (natype == ctx['global'].constants.NetworkAdapterType_I82540EM or
     1591          natype == ctx['global'].constants.NetworkAdapterType_I82545EM or
     1592          natype == ctx['global'].constants.NetworkAdapterType_I82543GC):
    15921593        return "e1000"
    1593     elif (type == ctx['global'].constants.NetworkAdapterType_Virtio):
     1594    elif (natype == ctx['global'].constants.NetworkAdapterType_Virtio):
    15941595        return "virtio"
    1595     elif (type == ctx['global'].constants.NetworkAdapterType_Null):
     1596    elif (natype == ctx['global'].constants.NetworkAdapterType_Null):
    15961597        return None
    15971598    else:
    1598         raise Exception("Unknown adapter type: "+type)
     1599        raise Exception("Unknown adapter type: "+natype)
    15991600
    16001601
     
    16031604        print "usage: portForward <vm> <adapter> <hostPort> <guestPort>"
    16041605        return 0
    1605     mach = argsToMach(ctx,args)
     1606    mach = argsToMach(ctx, args)
    16061607    if mach == None:
    16071608        return 0
     
    16341635        print "usage: showLog vm <num>"
    16351636        return 0
    1636     mach = argsToMach(ctx,args)
     1637    mach = argsToMach(ctx, args)
    16371638    if mach == None:
    16381639        return 0
     
    16401641    log = 0
    16411642    if (len(args) > 2):
    1642        log = args[2]
     1643        log = args[2]
    16431644
    16441645    uOffset = 0
     
    16571658        print "usage: findLog vm pattern <num>"
    16581659        return 0
    1659     mach = argsToMach(ctx,args)
     1660    mach = argsToMach(ctx, args)
    16601661    if mach == None:
    16611662        return 0
     
    16631664    log = 0
    16641665    if (len(args) > 3):
    1665        log = args[3]
     1666        log = args[3]
    16661667
    16671668    pattern = args[2]
     
    16741675        d = str(data).split("\n")
    16751676        for s in d:
    1676             m = re.findall(pattern, s)
    1677             if len(m) > 0:
    1678                 for mt in m:
    1679                     s = s.replace(mt, colored(mt,'red'))
     1677            match = re.findall(pattern, s)
     1678            if len(match) > 0:
     1679                for mt in match:
     1680                    s = s.replace(mt, colored(mt, 'red'))
    16801681                print s
    16811682        uOffset += len(data)
     
    16881689        print "usage: findAssert vm <num>"
    16891690        return 0
    1690     mach = argsToMach(ctx,args)
     1691    mach = argsToMach(ctx, args)
    16911692    if mach == None:
    16921693        return 0
     
    16941695    log = 0
    16951696    if (len(args) > 2):
    1696        log = args[2]
     1697        log = args[2]
    16971698
    16981699    uOffset = 0
     
    17141715                    context = context - 1
    17151716                continue
    1716             m = ere.findall(s)
    1717             if len(m) > 0:
     1717            match = ere.findall(s)
     1718            if len(match) > 0:
    17181719                active = True
    17191720                context = 50
     
    17241725
    17251726def evalCmd(ctx, args):
    1726    expr = ' '.join(args[1:])
    1727    try:
     1727    expr = ' '.join(args[1:])
     1728    try:
    17281729        exec expr
    1729    except Exception, e:
    1730         printErr(ctx,e)
    1731         if g_verbose:
     1730    except Exception, e:
     1731        printErr(ctx, e)
     1732        if g_fVerbose:
    17321733            traceback.print_exc()
    1733    return 0
     1734    return 0
    17341735
    17351736def reloadExtCmd(ctx, args):
    1736    # maybe will want more args smartness
    1737    checkUserExtensions(ctx, commands, getHomeFolder(ctx))
    1738    autoCompletion(commands, ctx)
    1739    return 0
     1737    # maybe will want more args smartness
     1738    checkUserExtensions(ctx, commands, getHomeFolder(ctx))
     1739    autoCompletion(commands, ctx)
     1740    return 0
    17401741
    17411742def runScriptCmd(ctx, args):
     
    17451746    try:
    17461747        lf = open(args[1], 'r')
    1747     except IOError,e:
    1748         print "cannot open:",args[1], ":",e
     1748    except IOError, e:
     1749        print "cannot open:", args[1], ":", e
    17491750        return 0
    17501751
     
    17601761                break
    17611762
    1762     except Exception,e:
    1763         printErr(ctx,e)
    1764         if g_verbose:
     1763    except Exception, e:
     1764        printErr(ctx, e)
     1765        if g_fVerbose:
    17651766            traceback.print_exc()
    17661767    lf.close()
     
    18211822    vbox = ctx['global'].platform.connect(url, user, passwd)
    18221823    ctx['vb'] = vbox
    1823     print "Running VirtualBox version %s" %(vbox.version)
     1824    try:
     1825        print "Running VirtualBox version %s" % (vbox.version)
     1826    except Exception, e:
     1827        printErr(ctx, e)
     1828        if g_fVerbose:
     1829            traceback.print_exc()
    18241830    ctx['perf'] = ctx['global'].getPerfCollector(ctx['vb'])
    18251831    return 0
     
    18531859        pass
    18541860
    1855     [url,user,passwd] = ctx['wsinfo']
     1861    [url, user, passwd] = ctx['wsinfo']
    18561862    ctx['vb'] = ctx['global'].platform.connect(url, user, passwd)
    1857     print "Running VirtualBox version %s" %(ctx['vb'].version)
     1863    try:
     1864        print "Running VirtualBox version %s" % (ctx['vb'].version)
     1865    except Exception, e:
     1866        printErr(ctx, e)
     1867        if g_fVerbose:
     1868            traceback.print_exc()
    18581869    return 0
    18591870
    18601871def exportVMCmd(ctx, args):
    1861     import sys
    1862 
    18631872    if len(args) < 3:
    18641873        print "usage: exportVm <machine> <path> <format> <license>"
    18651874        return 0
    1866     mach = argsToMach(ctx,args)
     1875    mach = argsToMach(ctx, args)
    18671876    if mach is None:
    18681877        return 0
    18691878    path = args[2]
    18701879    if (len(args) > 3):
    1871         format = args[3]
    1872     else:
    1873         format = "ovf-1.0"
     1880        fmt = args[3]
     1881    else:
     1882        fmt = "ovf-1.0"
    18741883    if (len(args) > 4):
    1875         license = args[4]
    1876     else:
    1877         license = "GPL"
     1884        lic = args[4]
     1885    else:
     1886        lic = "GPL"
    18781887
    18791888    app = ctx['vb'].createAppliance()
    18801889    desc = mach.export(app)
    1881     desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, license, "")
    1882     p = app.write(format, path)
    1883     if (progressBar(ctx, p) and int(p.resultCode) == 0):
    1884         print "Exported to %s in format %s" %(path, format)
    1885     else:
    1886         reportError(ctx,p)
     1890    desc.addDescription(ctx['global'].constants.VirtualSystemDescriptionType_License, lic, "")
     1891    progress = app.write(fmt, path)
     1892    if (progressBar(ctx, progress) and int(progress.resultCode) == 0):
     1893        print "Exported to %s in format %s" % (path, fmt)
     1894    else:
     1895        reportError(ctx, progress)
    18871896    return 0
    18881897
     
    19381947    '\n': 0x1c,
    19391948    '`':  0x29
    1940 };
     1949}
    19411950
    19421951extScancodes = {
     
    19781987    'DOWN':    [0xe0, 0x50],
    19791988    'RIGHT':   [0xe0, 0x4d],
    1980 };
     1989}
    19811990
    19821991def keyDown(ch):
     
    19861995    extCode = extScancodes.get(ch, [])
    19871996    if len(extCode) == 0:
    1988         print "bad ext",ch
     1997        print "bad ext", ch
    19891998    return extCode
    19901999
     
    19962005
    19972006def typeInGuest(console, text, delay):
    1998     import time
    19992007    pressed = []
    20002008    group = False
     
    20122020            # end group, release all keys
    20132021            for c in pressed:
    2014                  kbd.putScancodes(keyUp(c))
     2022                kbd.putScancodes(keyUp(c))
    20152023            pressed = []
    20162024            group = False
     
    20582066
    20592067def typeGuestCmd(ctx, args):
    2060     import sys
    2061 
    20622068    if len(args) < 3:
    20632069        print "usage: typeGuest <machine> <text> <charDelay>"
    20642070        return 0
    2065     mach =  argsToMach(ctx,args)
     2071    mach = argsToMach(ctx, args)
    20662072    if mach is None:
    20672073        return 0
     
    20742080        delay = 0.1
    20752081
    2076     gargs = [lambda ctx,mach,console,args: typeInGuest(console, text, delay)]
     2082    gargs = [lambda ctx, mach, console, args: typeInGuest(console, text, delay)]
    20772083    cmdExistingVm(ctx, mach, 'guestlambda', gargs)
    20782084
    20792085    return 0
    20802086
    2081 def optId(verbose,id):
    2082    if verbose:
    2083       return ": "+id
    2084    else:
    2085       return ""
    2086 
    2087 def asSize(val,inBytes):
    2088    if inBytes:
    2089       return int(val)/(1024*1024)
    2090    else:
    2091       return int(val)
    2092 
    2093 def listMediaCmd(ctx,args):
    2094    if len(args) > 1:
    2095       verbose = int(args[1])
    2096    else:
    2097       verbose = False
    2098    hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
    2099    print colCat(ctx,"Hard disks:")
    2100    for hdd in hdds:
    2101        if hdd.state != ctx['global'].constants.MediumState_Created:
    2102            hdd.refreshState()
    2103        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)))
    2104 
    2105    dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
    2106    print colCat(ctx,"CD/DVD disks:")
    2107    for dvd in dvds:
    2108        if dvd.state != ctx['global'].constants.MediumState_Created:
    2109            dvd.refreshState()
    2110        print "   %s (%s)%s %s" %(colPath(ctx,dvd.location), dvd.format,optId(verbose,dvd.id),colSizeM(ctx,asSize(dvd.size, True)))
    2111 
    2112    floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
    2113    print colCat(ctx,"Floppy disks:")
    2114    for floppy in floppys:
    2115        if floppy.state != ctx['global'].constants.MediumState_Created:
    2116            floppy.refreshState()
    2117        print "   %s (%s)%s %s" %(colPath(ctx,floppy.location), floppy.format,optId(verbose,floppy.id), colSizeM(ctx,asSize(floppy.size, True)))
    2118 
    2119    return 0
    2120 
    2121 def listUsbCmd(ctx,args):
    2122    if (len(args) > 1):
    2123       print "usage: listUsb"
    2124       return 0
    2125 
    2126    host = ctx['vb'].host
    2127    for ud in ctx['global'].getArray(host, 'USBDevices'):
    2128        printHostUsbDev(ctx,ud)
    2129 
    2130    return 0
    2131 
    2132 def findDevOfType(ctx,mach,type):
     2087def optId(verbose, uuid):
     2088    if verbose:
     2089        return ": "+uuid
     2090    else:
     2091        return ""
     2092
     2093def asSize(val, inBytes):
     2094    if inBytes:
     2095        return int(val)/(1024*1024)
     2096    else:
     2097        return int(val)
     2098
     2099def listMediaCmd(ctx, args):
     2100    if len(args) > 1:
     2101        verbose = int(args[1])
     2102    else:
     2103        verbose = False
     2104    hdds = ctx['global'].getArray(ctx['vb'], 'hardDisks')
     2105    print colCat(ctx, "Hard disks:")
     2106    for hdd in hdds:
     2107        if hdd.state != ctx['global'].constants.MediumState_Created:
     2108            hdd.refreshState()
     2109        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)))
     2110
     2111    dvds = ctx['global'].getArray(ctx['vb'], 'DVDImages')
     2112    print colCat(ctx, "CD/DVD disks:")
     2113    for dvd in dvds:
     2114        if dvd.state != ctx['global'].constants.MediumState_Created:
     2115            dvd.refreshState()
     2116        print "   %s (%s)%s %s" % (colPath(ctx, dvd.location), dvd.format, optId(verbose, dvd.id), colSizeM(ctx, asSize(dvd.size, True)))
     2117
     2118    floppys = ctx['global'].getArray(ctx['vb'], 'floppyImages')
     2119    print colCat(ctx, "Floppy disks:")
     2120    for floppy in floppys:
     2121        if floppy.state != ctx['global'].constants.MediumState_Created:
     2122            floppy.refreshState()
     2123        print "   %s (%s)%s %s" % (colPath(ctx, floppy.location), floppy.format, optId(verbose, floppy.id), colSizeM(ctx, asSize(floppy.size, True)))
     2124
     2125    return 0
     2126
     2127def listUsbCmd(ctx, args):
     2128    if (len(args) > 1):
     2129        print "usage: listUsb"
     2130        return 0
     2131
     2132    host = ctx['vb'].host
     2133    for ud in ctx['global'].getArray(host, 'USBDevices'):
     2134        printHostUsbDev(ctx, ud)
     2135
     2136    return 0
     2137
     2138def findDevOfType(ctx, mach, devtype):
    21332139    atts = ctx['global'].getArray(mach, 'mediumAttachments')
    21342140    for a in atts:
    2135         if a.type == type:
     2141        if a.type == devtype:
    21362142            return [a.controller, a.port, a.device]
    21372143    return [None, 0, 0]
    21382144
    2139 def createHddCmd(ctx,args):
    2140    if (len(args) < 3):
    2141       print "usage: createHdd sizeM location type"
    2142       return 0
    2143 
    2144    size = int(args[1])
    2145    loc = args[2]
    2146    if len(args) > 3:
    2147       format = args[3]
    2148    else:
    2149       format = "vdi"
    2150 
    2151    hdd = ctx['vb'].createHardDisk(format, loc)
    2152    progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))
    2153    if progressBar(ctx,progress) and hdd.id:
    2154        print "created HDD at %s as %s" %(colPath(ctx,hdd.location), hdd.id)
    2155    else:
    2156       print "cannot create disk (file %s exist?)" %(loc)
    2157       reportError(ctx,progress)
    2158       return 0
    2159 
    2160    return 0
    2161 
    2162 def registerHddCmd(ctx,args):
    2163    if (len(args) < 2):
    2164       print "usage: registerHdd location"
    2165       return 0
    2166 
    2167    vb = ctx['vb']
    2168    loc = args[1]
    2169    setImageId = False
    2170    imageId = ""
    2171    setParentId = False
    2172    parentId = ""
    2173    hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
    2174    print "registered HDD as %s" %(hdd.id)
    2175    return 0
    2176 
    2177 def controldevice(ctx,mach,args):
    2178     [ctr,port,slot,type,id] = args
    2179     mach.attachDevice(ctr, port, slot,type,id)
    2180 
    2181 def attachHddCmd(ctx,args):
    2182    if (len(args) < 3):
    2183       print "usage: attachHdd vm hdd controller port:slot"
    2184       return 0
    2185 
    2186    mach = argsToMach(ctx,args)
    2187    if mach is None:
    2188         return 0
    2189    vb = ctx['vb']
    2190    loc = args[2]
    2191    try:
    2192       hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
    2193    except:
    2194       print "no HDD with path %s registered" %(loc)
    2195       return 0
    2196    if len(args) > 3:
    2197        ctr = args[3]
    2198        (port,slot) = args[4].split(":")
    2199    else:
    2200        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
    2201 
    2202    cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk,hdd.id))
    2203    return 0
    2204 
    2205 def detachVmDevice(ctx,mach,args):
     2145def createHddCmd(ctx, args):
     2146    if (len(args) < 3):
     2147        print "usage: createHdd sizeM location type"
     2148        return 0
     2149
     2150    size = int(args[1])
     2151    loc = args[2]
     2152    if len(args) > 3:
     2153        fmt = args[3]
     2154    else:
     2155        fmt = "vdi"
     2156
     2157    hdd = ctx['vb'].createHardDisk(format, loc)
     2158    progress = hdd.createBaseStorage(size, (ctx['global'].constants.MediumVariant_Standard, ))
     2159    if progressBar(ctx,progress) and hdd.id:
     2160        print "created HDD at %s as %s" % (colPath(ctx,hdd.location), hdd.id)
     2161    else:
     2162       print "cannot create disk (file %s exist?)" % (loc)
     2163       reportError(ctx,progress)
     2164       return 0
     2165
     2166    return 0
     2167
     2168def registerHddCmd(ctx, args):
     2169    if (len(args) < 2):
     2170        print "usage: registerHdd location"
     2171        return 0
     2172
     2173    vbox = ctx['vb']
     2174    loc = args[1]
     2175    setImageId = False
     2176    imageId = ""
     2177    setParentId = False
     2178    parentId = ""
     2179    hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
     2180    print "registered HDD as %s" % (hdd.id)
     2181    return 0
     2182
     2183def controldevice(ctx, mach, args):
     2184    [ctr, port, slot, devtype, uuid] = args
     2185    mach.attachDevice(ctr, port, slot, devtype, uuid)
     2186
     2187def attachHddCmd(ctx, args):
     2188    if (len(args) < 3):
     2189        print "usage: attachHdd vm hdd controller port:slot"
     2190        return 0
     2191
     2192    mach = argsToMach(ctx, args)
     2193    if mach is None:
     2194        return 0
     2195    vbox = ctx['vb']
     2196    loc = args[2]
     2197    try:
     2198        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
     2199    except:
     2200        print "no HDD with path %s registered" % (loc)
     2201        return 0
     2202    if len(args) > 3:
     2203        ctr = args[3]
     2204        (port, slot) = args[4].split(":")
     2205    else:
     2206        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_HardDisk)
     2207
     2208    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_HardDisk, hdd.id))
     2209    return 0
     2210
     2211def detachVmDevice(ctx, mach, args):
    22062212    atts = ctx['global'].getArray(mach, 'mediumAttachments')
    22072213    hid = args[0]
     
    22112217                mach.detachDevice(a.controller, a.port, a.device)
    22122218
    2213 def detachMedium(ctx,mid,medium):
     2219def detachMedium(ctx, mid, medium):
    22142220    cmdClosedVm(ctx, machById(ctx, mid), detachVmDevice, [medium])
    22152221
    2216 def detachHddCmd(ctx,args):
    2217    if (len(args) < 3):
    2218       print "usage: detachHdd vm hdd"
    2219       return 0
    2220 
    2221    mach = argsToMach(ctx,args)
    2222    if mach is None:
    2223         return 0
    2224    vb = ctx['vb']
    2225    loc = args[2]
    2226    try:
    2227       hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
    2228    except:
    2229       print "no HDD with path %s registered" %(loc)
    2230       return 0
    2231 
    2232    detachMedium(ctx, mach.id, hdd)
    2233    return 0
    2234 
    2235 def unregisterHddCmd(ctx,args):
    2236    if (len(args) < 2):
    2237       print "usage: unregisterHdd path <vmunreg>"
    2238       return 0
    2239 
    2240    vb = ctx['vb']
    2241    loc = args[1]
    2242    if (len(args) > 2):
    2243       vmunreg = int(args[2])
    2244    else:
    2245       vmunreg = 0
    2246    try:
    2247       hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
    2248    except:
    2249       print "no HDD with path %s registered" %(loc)
    2250       return 0
    2251 
    2252    if vmunreg != 0:
    2253       machs = ctx['global'].getArray(hdd, 'machineIds')
    2254       try:
    2255          for m in machs:
    2256             print "Trying to detach from %s" %(m)
    2257             detachMedium(ctx, m, hdd)
    2258       except Exception, e:
    2259          print 'failed: ',e
    2260          return 0
    2261    hdd.close()
    2262    return 0
    2263 
    2264 def removeHddCmd(ctx,args):
    2265    if (len(args) != 2):
    2266       print "usage: removeHdd path"
    2267       return 0
    2268 
    2269    vb = ctx['vb']
    2270    loc = args[1]
    2271    try:
    2272       hdd = vb.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
    2273    except:
    2274       print "no HDD with path %s registered" %(loc)
    2275       return 0
    2276 
    2277    progress = hdd.deleteStorage()
    2278    progressBar(ctx,progress)
    2279 
    2280    return 0
    2281 
    2282 def registerIsoCmd(ctx,args):
    2283    if (len(args) < 2):
    2284       print "usage: registerIso location"
    2285       return 0
    2286    vb = ctx['vb']
    2287    loc = args[1]
    2288    iso = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2289    print "registered ISO as %s" %(iso.id)
    2290    return 0
    2291 
    2292 def unregisterIsoCmd(ctx,args):
    2293    if (len(args) != 2):
    2294       print "usage: unregisterIso path"
    2295       return 0
    2296 
    2297    vb = ctx['vb']
    2298    loc = args[1]
    2299    try:
    2300       dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2301    except:
    2302       print "no DVD with path %s registered" %(loc)
    2303       return 0
    2304 
    2305    progress = dvd.close()
    2306    print "Unregistered ISO at %s" %(colPath(ctx,loc))
    2307 
    2308    return 0
    2309 
    2310 def removeIsoCmd(ctx,args):
    2311    if (len(args) != 2):
    2312       print "usage: removeIso path"
    2313       return 0
    2314 
    2315    vb = ctx['vb']
    2316    loc = args[1]
    2317    try:
    2318       dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2319    except:
    2320       print "no DVD with path %s registered" %(loc)
    2321       return 0
    2322 
    2323    progress = dvd.deleteStorage()
    2324    if progressBar(ctx,progress):
    2325        print "Removed ISO at %s" %(colPath(ctx,dvd.location))
    2326    else:
    2327        reportError(ctx,progress)
    2328    return 0
    2329 
    2330 def attachIsoCmd(ctx,args):
    2331    if (len(args) < 3):
    2332       print "usage: attachIso vm iso controller port:slot"
    2333       return 0
    2334 
    2335    mach = argsToMach(ctx,args)
    2336    if mach is None:
    2337         return 0
    2338    vb = ctx['vb']
    2339    loc = args[2]
    2340    try:
    2341       dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2342    except:
    2343       print "no DVD with path %s registered" %(loc)
    2344       return 0
    2345    if len(args) > 3:
    2346        ctr = args[3]
    2347        (port,slot) = args[4].split(":")
    2348    else:
    2349        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
    2350    cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
    2351    return 0
    2352 
    2353 def detachIsoCmd(ctx,args):
    2354    if (len(args) < 3):
    2355       print "usage: detachIso vm iso"
    2356       return 0
    2357 
    2358    mach =  argsToMach(ctx,args)
    2359    if mach is None:
    2360         return 0
    2361    vb = ctx['vb']
    2362    loc = args[2]
    2363    try:
    2364       dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2365    except:
    2366       print "no DVD with path %s registered" %(loc)
    2367       return 0
    2368 
    2369    detachMedium(ctx, mach.id, dvd)
    2370    return 0
    2371 
    2372 def mountIsoCmd(ctx,args):
    2373    if (len(args) < 3):
    2374       print "usage: mountIso vm iso controller port:slot"
    2375       return 0
    2376 
    2377    mach = argsToMach(ctx,args)
    2378    if mach is None:
    2379         return 0
    2380    vb = ctx['vb']
    2381    loc = args[2]
    2382    try:
    2383       dvd = vb.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
    2384    except:
    2385       print "no DVD with path %s registered" %(loc)
    2386       return 0
    2387 
    2388    if len(args) > 3:
    2389        ctr = args[3]
    2390        (port,slot) = args[4].split(":")
    2391    else:
    2392        # autodetect controller and location, just find first controller with media == DVD
    2393        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
    2394 
    2395    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True])
    2396 
    2397    return 0
    2398 
    2399 def unmountIsoCmd(ctx,args):
    2400    if (len(args) < 2):
    2401       print "usage: unmountIso vm controller port:slot"
    2402       return 0
    2403 
    2404    mach = argsToMach(ctx,args)
    2405    if mach is None:
    2406         return 0
    2407    vb = ctx['vb']
    2408 
    2409    if len(args) > 3:
    2410        ctr = args[2]
    2411        (port,slot) = args[3].split(":")
    2412    else:
    2413        # autodetect controller and location, just find first controller with media == DVD
    2414        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
    2415 
    2416    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True])
    2417 
    2418    return 0
    2419 
    2420 def attachCtr(ctx,mach,args):
    2421     [name, bus, type] = args
     2222def detachHddCmd(ctx, args):
     2223    if (len(args) < 3):
     2224        print "usage: detachHdd vm hdd"
     2225        return 0
     2226
     2227    mach = argsToMach(ctx, args)
     2228    if mach is None:
     2229        return 0
     2230    vbox = ctx['vb']
     2231    loc = args[2]
     2232    try:
     2233        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
     2234    except:
     2235        print "no HDD with path %s registered" % (loc)
     2236        return 0
     2237
     2238    detachMedium(ctx, mach.id, hdd)
     2239    return 0
     2240
     2241def unregisterHddCmd(ctx, args):
     2242    if (len(args) < 2):
     2243        print "usage: unregisterHdd path <vmunreg>"
     2244        return 0
     2245
     2246    vbox = ctx['vb']
     2247    loc = args[1]
     2248    if (len(args) > 2):
     2249        vmunreg = int(args[2])
     2250    else:
     2251        vmunreg = 0
     2252    try:
     2253        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
     2254    except:
     2255        print "no HDD with path %s registered" % (loc)
     2256        return 0
     2257
     2258    if vmunreg != 0:
     2259        machs = ctx['global'].getArray(hdd, 'machineIds')
     2260        try:
     2261            for mach in machs:
     2262                print "Trying to detach from %s" % (mach)
     2263                detachMedium(ctx, mach, hdd)
     2264        except Exception, e:
     2265            print 'failed: ', e
     2266            return 0
     2267    hdd.close()
     2268    return 0
     2269
     2270def removeHddCmd(ctx, args):
     2271    if (len(args) != 2):
     2272        print "usage: removeHdd path"
     2273        return 0
     2274
     2275    vbox = ctx['vb']
     2276    loc = args[1]
     2277    try:
     2278        hdd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_HardDisk, ctx['global'].constants.AccessMode_ReadWrite, false)
     2279    except:
     2280        print "no HDD with path %s registered" % (loc)
     2281        return 0
     2282
     2283    progress = hdd.deleteStorage()
     2284    progressBar(ctx, progress)
     2285
     2286    return 0
     2287
     2288def registerIsoCmd(ctx, args):
     2289    if (len(args) < 2):
     2290        print "usage: registerIso location"
     2291        return 0
     2292
     2293    vbox = ctx['vb']
     2294    loc = args[1]
     2295    iso = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2296    print "registered ISO as %s" % (iso.id)
     2297    return 0
     2298
     2299def unregisterIsoCmd(ctx, args):
     2300    if (len(args) != 2):
     2301        print "usage: unregisterIso path"
     2302        return 0
     2303
     2304    vbox = ctx['vb']
     2305    loc = args[1]
     2306    try:
     2307        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2308    except:
     2309        print "no DVD with path %s registered" % (loc)
     2310        return 0
     2311
     2312    progress = dvd.close()
     2313    print "Unregistered ISO at %s" % (colPath(ctx, loc))
     2314
     2315    return 0
     2316
     2317def removeIsoCmd(ctx, args):
     2318    if (len(args) != 2):
     2319        print "usage: removeIso path"
     2320        return 0
     2321
     2322    vbox = ctx['vb']
     2323    loc = args[1]
     2324    try:
     2325        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2326    except:
     2327        print "no DVD with path %s registered" % (loc)
     2328        return 0
     2329
     2330    progress = dvd.deleteStorage()
     2331    if progressBar(ctx, progress):
     2332        print "Removed ISO at %s" % (colPath(ctx, dvd.location))
     2333    else:
     2334        reportError(ctx, progress)
     2335    return 0
     2336
     2337def attachIsoCmd(ctx, args):
     2338    if (len(args) < 3):
     2339        print "usage: attachIso vm iso controller port:slot"
     2340        return 0
     2341
     2342    mach = argsToMach(ctx, args)
     2343    if mach is None:
     2344        return 0
     2345    vbox = ctx['vb']
     2346    loc = args[2]
     2347    try:
     2348        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2349    except:
     2350        print "no DVD with path %s registered" % (loc)
     2351        return 0
     2352    if len(args) > 3:
     2353        ctr = args[3]
     2354        (port, slot) = args[4].split(":")
     2355    else:
     2356        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
     2357    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.attachDevice(ctr, port, slot, ctx['global'].constants.DeviceType_DVD, dvd))
     2358    return 0
     2359
     2360def detachIsoCmd(ctx, args):
     2361    if (len(args) < 3):
     2362        print "usage: detachIso vm iso"
     2363        return 0
     2364
     2365    mach = argsToMach(ctx, args)
     2366    if mach is None:
     2367        return 0
     2368    vbox = ctx['vb']
     2369    loc = args[2]
     2370    try:
     2371        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2372    except:
     2373        print "no DVD with path %s registered" % (loc)
     2374        return 0
     2375
     2376    detachMedium(ctx, mach.id, dvd)
     2377    return 0
     2378
     2379def mountIsoCmd(ctx, args):
     2380    if (len(args) < 3):
     2381        print "usage: mountIso vm iso controller port:slot"
     2382        return 0
     2383
     2384    mach = argsToMach(ctx, args)
     2385    if mach is None:
     2386        return 0
     2387    vbox = ctx['vb']
     2388    loc = args[2]
     2389    try:
     2390        dvd = vbox.openMedium(loc, ctx['global'].constants.DeviceType_DVD, ctx['global'].constants.AccessMode_ReadOnly, false)
     2391    except:
     2392        print "no DVD with path %s registered" % (loc)
     2393        return 0
     2394
     2395    if len(args) > 3:
     2396        ctr = args[3]
     2397        (port, slot) = args[4].split(":")
     2398    else:
     2399        # autodetect controller and location, just find first controller with media == DVD
     2400        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
     2401
     2402    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, dvd, True])
     2403
     2404    return 0
     2405
     2406def unmountIsoCmd(ctx, args):
     2407    if (len(args) < 2):
     2408        print "usage: unmountIso vm controller port:slot"
     2409        return 0
     2410
     2411    mach = argsToMach(ctx, args)
     2412    if mach is None:
     2413        return 0
     2414    vbox = ctx['vb']
     2415
     2416    if len(args) > 3:
     2417        ctr = args[2]
     2418        (port, slot) = args[3].split(":")
     2419    else:
     2420        # autodetect controller and location, just find first controller with media == DVD
     2421        [ctr, port, slot] = findDevOfType(ctx, mach, ctx['global'].constants.DeviceType_DVD)
     2422
     2423    cmdExistingVm(ctx, mach, 'mountiso', [ctr, port, slot, None, True])
     2424
     2425    return 0
     2426
     2427def attachCtr(ctx, mach, args):
     2428    [name, bus, ctrltype] = args
    24222429    ctr = mach.addStorageController(name, bus)
    2423     if type != None:
    2424         ctr.controllerType = type
    2425 
    2426 def attachCtrCmd(ctx,args):
    2427    if (len(args) < 4):
    2428       print "usage: attachCtr vm cname bus <type>"
    2429       return 0
    2430 
    2431    if len(args) > 4:
    2432        type = enumFromString(ctx,'StorageControllerType', args[4])
    2433        if type == None:
    2434            print "Controller type %s unknown" %(args[4])
    2435            return 0
    2436    else:
    2437        type = None
    2438 
    2439    mach = argsToMach(ctx,args)
    2440    if mach is None:
    2441         return 0
    2442    bus = enumFromString(ctx,'StorageBus', args[3])
    2443    if bus is None:
    2444        print "Bus type %s unknown" %(args[3])
    2445        return 0
    2446    name = args[2]
    2447    cmdClosedVm(ctx, mach, attachCtr, [name, bus, type])
    2448    return 0
    2449 
    2450 def detachCtrCmd(ctx,args):
    2451    if (len(args) < 3):
    2452       print "usage: detachCtr vm name"
    2453       return 0
    2454 
    2455    mach = argsToMach(ctx,args)
    2456    if mach is None:
    2457         return 0
    2458    ctr = args[2]
    2459    cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeStorageController(ctr))
    2460    return 0
    2461 
    2462 def usbctr(ctx,mach,console,args):
     2430    if ctrltype != None:
     2431        ctr.controllerType = ctrltype
     2432
     2433def attachCtrCmd(ctx, args):
     2434    if (len(args) < 4):
     2435        print "usage: attachCtr vm cname bus <type>"
     2436        return 0
     2437
     2438    if len(args) > 4:
     2439        ctrltype = enumFromString(ctx, 'StorageControllerType', args[4])
     2440        if ctrltype == None:
     2441            print "Controller type %s unknown" % (args[4])
     2442            return 0
     2443    else:
     2444        ctrltype = None
     2445
     2446    mach = argsToMach(ctx, args)
     2447    if mach is None:
     2448        return 0
     2449    bus = enumFromString(ctx, 'StorageBus', args[3])
     2450    if bus is None:
     2451        print "Bus type %s unknown" % (args[3])
     2452        return 0
     2453    name = args[2]
     2454    cmdClosedVm(ctx, mach, attachCtr, [name, bus, ctrltype])
     2455    return 0
     2456
     2457def detachCtrCmd(ctx, args):
     2458    if (len(args) < 3):
     2459        print "usage: detachCtr vm name"
     2460        return 0
     2461
     2462    mach = argsToMach(ctx, args)
     2463    if mach is None:
     2464        return 0
     2465    ctr = args[2]
     2466    cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeStorageController(ctr))
     2467    return 0
     2468
     2469def usbctr(ctx, mach, console, args):
    24632470    if (args[0]):
    24642471        console.attachUSBDevice(args[1])
     
    24662473        console.detachUSBDevice(args[1])
    24672474
    2468 def attachUsbCmd(ctx,args):
    2469    if (len(args) < 3):
    2470       print "usage: attachUsb vm deviceuid"
    2471       return 0
    2472 
    2473    mach = argsToMach(ctx,args)
    2474    if mach is None:
    2475         return 0
    2476    dev = args[2]
    2477    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,True,dev])
    2478    return 0
    2479 
    2480 def detachUsbCmd(ctx,args):
    2481    if (len(args) < 3):
    2482       print "usage: detachUsb vm deviceuid"
    2483       return 0
    2484 
    2485    mach = argsToMach(ctx,args)
    2486    if mach is None:
    2487         return 0
    2488    dev = args[2]
    2489    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr,False,dev])
    2490    return 0
    2491 
    2492 
    2493 def guiCmd(ctx,args):
    2494    if (len(args) > 1):
    2495       print "usage: gui"
    2496       return 0
    2497 
    2498    binDir = ctx['global'].getBinDir()
    2499 
    2500    vbox = os.path.join(binDir, 'VirtualBox')
    2501    try:
     2475def attachUsbCmd(ctx, args):
     2476    if (len(args) < 3):
     2477        print "usage: attachUsb vm deviceuid"
     2478        return 0
     2479
     2480    mach = argsToMach(ctx, args)
     2481    if mach is None:
     2482        return 0
     2483    dev = args[2]
     2484    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, True, dev])
     2485    return 0
     2486
     2487def detachUsbCmd(ctx, args):
     2488    if (len(args) < 3):
     2489        print "usage: detachUsb vm deviceuid"
     2490        return 0
     2491
     2492    mach = argsToMach(ctx, args)
     2493    if mach is None:
     2494        return 0
     2495    dev = args[2]
     2496    cmdExistingVm(ctx, mach, 'guestlambda', [usbctr, False, dev])
     2497    return 0
     2498
     2499
     2500def guiCmd(ctx, args):
     2501    if (len(args) > 1):
     2502        print "usage: gui"
     2503        return 0
     2504
     2505    binDir = ctx['global'].getBinDir()
     2506
     2507    vbox = os.path.join(binDir, 'VirtualBox')
     2508    try:
    25022509        os.system(vbox)
    2503    except KeyboardInterrupt:
     2510    except KeyboardInterrupt:
    25042511        # to allow interruption
    25052512        pass
    2506    return 0
    2507 
    2508 def shareFolderCmd(ctx,args):
     2513    return 0
     2514
     2515def shareFolderCmd(ctx, args):
    25092516    if (len(args) < 4):
    25102517        print "usage: shareFolder vm path name <writable> <persistent>"
    25112518        return 0
    25122519
    2513     mach = argsToMach(ctx,args)
     2520    mach = argsToMach(ctx, args)
    25142521    if mach is None:
    25152522        return 0
     
    25252532                persistent = True
    25262533    if persistent:
    2527         cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
    2528     else:
    2529         cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
    2530     return 0
    2531 
    2532 def unshareFolderCmd(ctx,args):
     2534        cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.createSharedFolder(name, path, writable), [])
     2535    else:
     2536        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.createSharedFolder(name, path, writable)])
     2537    return 0
     2538
     2539def unshareFolderCmd(ctx, args):
    25332540    if (len(args) < 3):
    25342541        print "usage: unshareFolder vm name"
    25352542        return 0
    25362543
    2537     mach = argsToMach(ctx,args)
     2544    mach = argsToMach(ctx, args)
    25382545    if mach is None:
    25392546        return 0
     
    25422549    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
    25432550        if sf.name == name:
    2544             cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
     2551            cmdClosedVm(ctx, mach, lambda ctx, mach, args: mach.removeSharedFolder(name), [])
    25452552            found = True
    25462553            break
    25472554    if not found:
    2548         cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
    2549     return 0
    2550 
    2551 
    2552 def snapshotCmd(ctx,args):
     2555        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args: console.removeSharedFolder(name)])
     2556    return 0
     2557
     2558
     2559def snapshotCmd(ctx, args):
    25532560    if (len(args) < 2 or args[1] == 'help'):
    25542561        print "Take snapshot:    snapshot vm take name <description>"
     
    25572564        return 0
    25582565
    2559     mach = argsToMach(ctx,args)
     2566    mach = argsToMach(ctx, args)
    25602567    if mach is None:
    25612568        return 0
     
    25702577        else:
    25712578            desc = ""
    2572         cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.takeSnapshot(name,desc)))
     2579        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.takeSnapshot(name, desc)))
    25732580        return 0
    25742581
     
    25792586        name = args[3]
    25802587        snap = mach.findSnapshot(name)
    2581         cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
     2588        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.restoreSnapshot(snap)))
    25822589        return 0
    25832590
     
    25872594            return 0
    25882595        snap = mach.currentSnapshot()
    2589         cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.restoreSnapshot(snap)))
     2596        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.restoreSnapshot(snap)))
    25902597        return 0
    25912598
     
    25962603        name = args[3]
    25972604        snap = mach.findSnapshot(name)
    2598         cmdAnyVm(ctx, mach, lambda ctx,mach,console,args: progressBar(ctx, console.deleteSnapshot(snap.id)))
    2599         return 0
    2600 
    2601     print "Command '%s' is unknown" %(cmd)
     2605        cmdAnyVm(ctx, mach, lambda ctx, mach, console, args: progressBar(ctx, console.deleteSnapshot(snap.id)))
     2606        return 0
     2607
     2608    print "Command '%s' is unknown" % (cmd)
    26022609    return 0
    26032610
     
    26372644                    print natAlias.__doc__
    26382645                    return (1, None)
    2639                 nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
     2646                nat.aliasMode = int(nat.aliasMode) | alias[args[a]]
    26402647    return (0, None)
    26412648
     
    26482655    """
    26492656    if len(args) == 1:
    2650         (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
     2657        (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings()
    26512658        if mtu == 0: mtu = 1500
    26522659        if socksndbuf == 0: socksndbuf = 64
     
    26542661        if tcpsndwnd == 0: tcpsndwnd = 64
    26552662        if tcprcvwnd == 0: tcprcvwnd = 64
    2656         msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
     2663        msg = 'mtu:%s socket(snd:%s, rcv:%s) tcpwnd(snd:%s, rcv:%s)' % (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd)
    26572664        return (0, [msg])
    26582665    else:
     
    26872694    else:
    26882695        nat.DNSPassDomain = 'passdomain' in args
    2689         nat.DNSProxy =  'proxy' in args
    2690         nat.DNSUseHostResolver =  'usehostresolver' in args
     2696        nat.DNSProxy = 'proxy' in args
     2697        nat.DNSUseHostResolver = 'usehostresolver' in args
    26912698    return (0, None)
    26922699
     
    27042711            if server is None:
    27052712                server = '10.0.%d/24' % (int(nicnum) + 2)
    2706             (server,mask) = server.split('/')
     2713            (server, mask) = server.split('/')
    27072714            while server.count('.') != 3:
    27082715                server += '.0'
    2709             (a,b,c,d) = server.split('.')
    2710             server = '%d.%d.%d.4' % (a,b,c)
     2716            (a, b, c, d) = server.split('.')
     2717            server = '%d.%d.%d.4' % (a, b, c)
    27112718        prefix = nat.TFTPPrefix
    27122719        if prefix is None:
     
    27462753        pfs = ctx['global'].getArray(nat, 'redirects')
    27472754        for pf in pfs:
    2748             (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
     2755            (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(', ')
    27492756            msg.append('%s: %s %s:%s => %s:%s' % (pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
    27502757        return (0, msg) # msg is array
     
    28412848    if len(cmdargs) > 1:
    28422849        rosession = 0
    2843         session = ctx['global'].openMachineSession(mach, False);
    2844         mach = session.machine;
     2850        session = ctx['global'].openMachineSession(mach, False)
     2851        mach = session.machine
    28452852
    28462853    adapter = mach.getNetworkAdapter(nicnum)
     
    28842891def nicLineSpeedSubCmd(ctx, vm, nicnum, adapter, args):
    28852892    if len(args) == 1:
    2886         r = '%d kbps'%(adapter.lineSpeed)
     2893        r = '%d kbps'% (adapter.lineSpeed)
    28872894        return (0, r)
    28882895    else:
     
    29112918    if len(args) == 1:
    29122919        nictypes = ctx['const'].all_values('NetworkAdapterType')
    2913         for n in nictypes.keys():
    2914             if str(adapter.adapterType) == str(nictypes[n]):
    2915                 return (0, str(n))
     2920        for key in nictypes.keys():
     2921            if str(adapter.adapterType) == str(nictypes[key]):
     2922                return (0, str(key))
    29162923        return (1, None)
    29172924    else:
     
    30143021    if    len(args) < 3 \
    30153022       or int(args[2]) not in range(0, ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType)):
    3016             print 'please specify adapter num %d isn\'t in range [0-%d]'%(args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))
    3017             return 0
     3023        print 'please specify adapter num %d isn\'t in range [0-%d]'% (args[2], ctx['vb'].systemProperties.getMaxNetworkAdapters(vm.chipsetType))
     3024        return 0
    30183025    nicnum = int(args[2])
    30193026    cmdargs = args[3:]
     
    30253032    (rc, report) = niccomand[func](ctx, vm, nicnum, adapter, cmdargs)
    30263033    if rc == 0:
    3027             vm.saveSettings()
     3034        vm.saveSettings()
    30283035    if report is not None:
    30293036        print '%s nic %d %s: %s' % (vm.name, nicnum, args[3], report)
     
    30343041def promptCmd(ctx, args):
    30353042    if    len(args) < 2:
    3036         print "Current prompt: '%s'" %(ctx['prompt'])
     3043        print "Current prompt: '%s'" % (ctx['prompt'])
    30373044        return 0
    30383045
     
    30473054    scope = args[1]
    30483055    cmd = args[2]
    3049     elems = eval_xpath(ctx,scope)
     3056    elems = eval_xpath(ctx, scope)
    30503057    try:
    30513058        for e in elems:
     
    30623069    cmdargs = args[1:]
    30633070    cmdargs.insert(1, '')
    3064     for m in getMachines(ctx):
    3065         cmdargs[1] = m.id
     3071    for mach in getMachines(ctx):
     3072        cmdargs[1] = mach.id
    30663073        runCommandArgs(ctx, cmdargs)
    30673074    return 0
     
    30713078        print "usage: recordDemo vm filename (duration)"
    30723079        return 0
    3073     mach = argsToMach(ctx,args)
     3080    mach = argsToMach(ctx, args)
    30743081    if mach == None:
    30753082        return 0
     
    30783085    if len(args) > 3:
    30793086        dur = float(args[3])
    3080     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  recordDemo(ctx, console, filename, dur)])
     3087    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  recordDemo(ctx, console, filename, dur)])
    30813088    return 0
    30823089
     
    30853092        print "usage: playbackDemo vm filename (duration)"
    30863093        return 0
    3087     mach = argsToMach(ctx,args)
     3094    mach = argsToMach(ctx, args)
    30883095    if mach == None:
    30893096        return 0
     
    30923099    if len(args) > 3:
    30933100        dur = float(args[3])
    3094     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  playbackDemo(ctx, console, filename, dur)])
    3095     return 0
    3096 
    3097 
    3098 def pciAddr(ctx,addr):
    3099     str = "%02x:%02x.%d" %(addr >> 8, (addr & 0xff) >> 3, addr & 7)
    3100     return colPci(ctx, str)
     3101    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  playbackDemo(ctx, console, filename, dur)])
     3102    return 0
     3103
     3104
     3105def pciAddr(ctx, addr):
     3106    strg = "%02x:%02x.%d" % (addr >> 8, (addr & 0xff) >> 3, addr & 7)
     3107    return colPci(ctx, strg)
    31013108
    31023109def lspci(ctx, console):
     
    31043111    for a in assigned:
    31053112        if a.isPhysicalDevice:
    3106             print "%s: assigned host device %s guest %s" %(colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress))
     3113            print "%s: assigned host device %s guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.hostAddress), pciAddr(ctx, a.guestAddress))
    31073114
    31083115    atts = ctx['global'].getArray(console, 'attachedPCIDevices')
    31093116    for a in atts:
    31103117        if a.isPhysicalDevice:
    3111             print "%s: physical, guest %s, host %s" %(colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress))
     3118            print "%s: physical, guest %s, host %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress), pciAddr(ctx, a.hostAddress))
    31123119        else:
    3113             print "%s: virtual, guest %s" %(colDev(ctx, a.name), pciAddr(ctx, a.guestAddress))
     3120            print "%s: virtual, guest %s" % (colDev(ctx, a.name), pciAddr(ctx, a.guestAddress))
    31143121    return
    31153122
    3116 def parsePci(str):
     3123def parsePci(strg):
    31173124    pcire = re.compile(r'(?P<b>[0-9a-fA-F]+):(?P<d>[0-9a-fA-F]+)\.(?P<f>\d)')
    3118     m = pcire.search(str)
    3119     if m is None:
     3125    match = pcire.search(strg)
     3126    if match is None:
    31203127        return -1
    3121     dict = m.groupdict()
    3122     return ((int(dict['b'], 16)) << 8) | ((int(dict['d'], 16)) << 3) | int(dict['f'])
     3128    pdict = match.groupdict()
     3129    return ((int(pdict['b'], 16)) << 8) | ((int(pdict['d'], 16)) << 3) | int(pdict['f'])
    31233130
    31243131def lspciCmd(ctx, args):
     
    31263133        print "usage: lspci vm"
    31273134        return 0
    3128     mach = argsToMach(ctx,args)
    3129     if mach == None:
    3130         return 0
    3131     cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args:  lspci(ctx, console)])
     3135    mach = argsToMach(ctx, args)
     3136    if mach == None:
     3137        return 0
     3138    cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx, mach, console, args:  lspci(ctx, console)])
    31323139    return 0
    31333140
     
    31363143        print "usage: attachpci vm hostpci <guestpci>"
    31373144        return 0
    3138     mach = argsToMach(ctx,args)
     3145    mach = argsToMach(ctx, args)
    31393146    if mach == None:
    31403147        return 0
    31413148    hostaddr = parsePci(args[2])
    31423149    if hostaddr == -1:
    3143         print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[2])
     3150        print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])
    31443151        return 0
    31453152
     
    31473154        guestaddr = parsePci(args[3])
    31483155        if guestaddr == -1:
    3149             print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[3])
     3156            print "invalid guest PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[3])
    31503157            return 0
    31513158    else:
    31523159        guestaddr = hostaddr
    3153     cmdClosedVm(ctx, mach, lambda ctx,mach,a: mach.attachHostPCIDevice(hostaddr, guestaddr, True))
     3160    cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.attachHostPCIDevice(hostaddr, guestaddr, True))
    31543161    return 0
    31553162
     
    31583165        print "usage: detachpci vm hostpci"
    31593166        return 0
    3160     mach = argsToMach(ctx,args)
     3167    mach = argsToMach(ctx, args)
    31613168    if mach == None:
    31623169        return 0
    31633170    hostaddr = parsePci(args[2])
    31643171    if hostaddr == -1:
    3165         print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" %(args[2])
    3166         return 0
    3167 
    3168     cmdClosedVm(ctx, mach, lambda ctx,mach,a: mach.detachHostPCIDevice(hostaddr))
     3172        print "invalid host PCI %s, accepted format 01:02.3 for bus 1, device 2, function 3" % (args[2])
     3173        return 0
     3174
     3175    cmdClosedVm(ctx, mach, lambda ctx, mach, a: mach.detachHostPCIDevice(hostaddr))
    31693176    return 0
    31703177
     
    32083215            'verbose':['Toggle verbosity', verboseCmd, 0],
    32093216            'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd, 0],
    3210             'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"\'', evalCmd, 0],
     3217            'eval':['Evaluate arbitrary Python construction: eval \'for m in getMachines(ctx): print m.name, "has", m.memorySize, "M"\'', evalCmd, 0],
    32113218            'quit':['Exits', quitCmd, 0],
    32123219            'host':['Show host information', hostCmd, 0],
     
    32293236            'typeGuest':['Type arbitrary text in guest: typeGuest Linux "^lls\\n&UP;&BKSP;ess /etc/hosts\\nq^c" 0.7', typeGuestCmd, 0],
    32303237            'openportal':['Open portal for teleportation of VM from another box (see teleport): openportal Win 8000 <passwd>', openportalCmd, 0],
    3231             'closeportal':['Close teleportation portal (see openportal,teleport): closeportal Win', closeportalCmd, 0],
     3238            'closeportal':['Close teleportation portal (see openportal, teleport): closeportal Win', closeportalCmd, 0],
    32323239            'getextra':['Get extra data, empty key lists all: getextra <vm|global> <key>', getExtraDataCmd, 0],
    32333240            'setextra':['Set extra data, empty value removes key: setextra <vm|global> <key> <value>', setExtraDataCmd, 0],
     
    32763283    if aliases.get(c, None) != None:
    32773284        c = aliases[c]
    3278     ci = commands.get(c,None)
     3285    ci = commands.get(c, None)
    32793286    if ci == None:
    3280         print "Unknown command: '%s', type 'help' for list of known commands" %(c)
     3287        print "Unknown command: '%s', type 'help' for list of known commands" % (c)
    32813288        return 0
    32823289    if ctx['remote'] and ctx['vb'] is None:
    32833290        if c not in ['connect', 'reconnect', 'help', 'quit']:
    3284             print "First connect to remote server with %s command." %(colored('connect', 'blue'))
     3291            print "First connect to remote server with %s command." % (colored('connect', 'blue'))
    32853292            return 0
    32863293    return ci[1](ctx, args)
     
    33103317# they will also be picked up, so this way one can exchange
    33113318# shell extensions easily.
    3312 def addExtsFromFile(ctx, cmds, file):
    3313     if not os.path.isfile(file):
     3319def addExtsFromFile(ctx, cmds, filename):
     3320    if not os.path.isfile(filename):
    33143321        return
    33153322    d = {}
    33163323    try:
    3317         execfile(file, d, d)
    3318         for (k,v) in d['commands'].items():
    3319             if g_verbose:
    3320                 print "customize: adding \"%s\" - %s" %(k, v[0])
    3321             cmds[k] = [v[0], v[1], file]
     3324        execfile(filename, d, d)
     3325        for (k, v) in d['commands'].items():
     3326            if g_fVerbose:
     3327                print "customize: adding \"%s\" - %s" % (k, v[0])
     3328            cmds[k] = [v[0], v[1], filename]
    33223329    except:
    3323         print "Error loading user extensions from %s" %(file)
     3330        print "Error loading user extensions from %s" % (filename)
    33243331        traceback.print_exc()
    33253332
     
    33373344        # not editor temporary files, please.
    33383345        if e.endswith('.py'):
    3339             addExtsFromFile(ctx, cmds, os.path.join(shextdir,e))
     3346            addExtsFromFile(ctx, cmds, os.path.join(shextdir, e))
    33403347
    33413348def getHomeFolder(ctx):
     
    33563363    vbox = ctx['vb']
    33573364    if vbox is not None:
    3358         print "Running VirtualBox version %s" %(vbox.version)
     3365        try:
     3366            print "Running VirtualBox version %s" % (vbox.version)
     3367        except Exception, e:
     3368            printErr(ctx, e)
     3369            if g_fVerbose:
     3370                traceback.print_exc()
    33593371        ctx['perf'] = None # ctx['global'].getPerfCollector(vbox)
    33603372    else:
     
    33643376    checkUserExtensions(ctx, commands, home)
    33653377    if platform.system() in ['Windows', 'Microsoft']:
    3366         global g_hascolors
    3367         g_hascolors = False
    3368     hist_file=os.path.join(home, ".vboxshellhistory")
     3378        global g_fHasColors
     3379        g_fHasColors = False
     3380    hist_file = os.path.join(home, ".vboxshellhistory")
    33693381    autoCompletion(commands, ctx)
    33703382
    3371     if g_hasreadline and os.path.exists(hist_file):
     3383    if g_fHasReadline and os.path.exists(hist_file):
    33723384        readline.read_history_file(hist_file)
    33733385
     
    33753387    # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
    33763388    if ctx['perf']:
    3377       try:
    3378         ctx['perf'].setup(['*'], [vbox.host], 10, 15)
    3379       except:
    3380         pass
     3389        try:
     3390            ctx['perf'].setup(['*'], [vbox.host], 10, 15)
     3391        except:
     3392            pass
    33813393    cmds = []
    33823394
    3383     if g_cmd is not None:
    3384         cmds = g_cmd.split(';')
     3395    if g_sCmd is not None:
     3396        cmds = g_sCmd.split(';')
    33853397    it = cmds.__iter__()
    33863398
    33873399    while True:
    33883400        try:
    3389             if g_batchmode:
    3390                 cmd = 'runScript %s'%(g_scripfile)
    3391             elif g_cmd is not None:
     3401            if g_fBatchMode:
     3402                cmd = 'runScript %s'% (g_sScriptFile)
     3403            elif g_sCmd is not None:
    33923404                cmd = it.next()
    33933405            else:
     
    33953407            done = runCommand(ctx, cmd)
    33963408            if done != 0: break
    3397             if g_batchmode:
     3409            if g_fBatchMode:
    33983410                break
    33993411        except KeyboardInterrupt:
     
    34033415        except EOFError:
    34043416            break
    3405         except Exception,e:
    3406             printErr(ctx,e)
    3407             if g_verbose:
     3417        except Exception, e:
     3418            printErr(ctx, e)
     3419            if g_fVerbose:
    34083420                traceback.print_exc()
    34093421        ctx['global'].waitForEvents(0)
     
    34113423        # There is no need to disable metric collection. This is just an example.
    34123424        if ct['perf']:
    3413            ctx['perf'].disable(['*'], [vbox.host])
     3425            ctx['perf'].disable(['*'], [vbox.host])
    34143426    except:
    34153427        pass
    3416     if g_hasreadline:
     3428    if g_fHasReadline:
    34173429        readline.write_history_file(hist_file)
    34183430
     
    34213433    return runCommandArgs(ctx, args)
    34223434
    3423 def runGuestCommandCb(ctx, id, guestLambda, args):
    3424     mach =  machById(ctx,id)
     3435def runGuestCommandCb(ctx, uuid, guestLambda, args):
     3436    mach = machById(ctx, uuid)
    34253437    if mach == None:
    34263438        return 0
     
    34413453    parse.add_option("-c", dest="command_line", help = "command sequence to execute")
    34423454    parse.add_option("-o", dest="opt_line", help = "option line")
    3443     global g_verbose, g_scripfile, g_batchmode, g_hascolors, g_hasreadline, g_cmd
     3455    global g_fVerbose, g_sScriptFile, g_fBatchMode, g_fHasColors, g_fHasReadline, g_sCmd
    34443456    (options, args) = parse.parse_args()
    3445     g_verbose = options.verbose
     3457    g_fVerbose = options.verbose
    34463458    style = options.style
    34473459    if options.batch_file is not None:
    3448         g_batchmode = True
    3449         g_hascolors = False
    3450         g_hasreadline = False
    3451         g_scripfile = options.batch_file
     3460        g_fBatchMode = True
     3461        g_fHasColors = False
     3462        g_fHasReadline = False
     3463        g_sScriptFile = options.batch_file
    34523464    if options.command_line is not None:
    3453         g_hascolors = False
    3454         g_hasreadline = False
    3455         g_cmd = options.command_line
     3465        g_fHasColors = False
     3466        g_fHasReadline = False
     3467        g_sCmd = options.command_line
    34563468    if options.opt_line is not None:
    34573469        params = {}
    34583470        strparams = options.opt_line
    3459         l = strparams.split(',')
    3460         for e in l:
    3461             (k,v) = e.split('=')
    3462             params[k] = v
     3471        strparamlist = strparams.split(',')
     3472        for strparam in strparamlist:
     3473            (key, value) = strparam.split('=')
     3474            params[key] = value
    34633475    else:
    34643476        params = None
     
    34693481        if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
    34703482            vpp = cwd
    3471             print "Autodetected VBOX_PROGRAM_PATH as",vpp
     3483            print "Autodetected VBOX_PROGRAM_PATH as", vpp
    34723484            os.environ["VBOX_PROGRAM_PATH"] = vpp
    34733485            sys.path.append(os.path.join(vpp, "sdk", "installer"))
     
    34783490            vsp = os.path.join(vpp, "sdk")
    34793491        if vsp is not None :
    3480             print "Autodetected VBOX_SDK_PATH as",vsp
     3492            print "Autodetected VBOX_SDK_PATH as", vsp
    34813493            os.environ["VBOX_SDK_PATH"] = vsp
    34823494
    34833495    from vboxapi import VirtualBoxManager
    3484     g_virtualBoxManager = VirtualBoxManager(style, params)
    3485     ctx = {'global':g_virtualBoxManager,
    3486            'mgr':g_virtualBoxManager.mgr,
    3487            'vb':g_virtualBoxManager.vbox,
    3488            'const':g_virtualBoxManager.constants,
    3489            'remote':g_virtualBoxManager.remote,
    3490            'type':g_virtualBoxManager.type,
    3491            'run': lambda cmd,args: runCommandCb(ctx, cmd, args),
    3492            'guestlambda': lambda id,guestLambda,args: runGuestCommandCb(ctx, id, guestLambda, args),
    3493            'machById': lambda id: machById(ctx,id),
    3494            'argsToMach': lambda args: argsToMach(ctx,args),
    3495            'progressBar': lambda p: progressBar(ctx,p),
     3496    virtualBoxManager = VirtualBoxManager(style, params)
     3497    ctx = {'global':virtualBoxManager,
     3498           'mgr':virtualBoxManager.mgr,
     3499           'vb':virtualBoxManager.vbox,
     3500           'const':virtualBoxManager.constants,
     3501           'remote':virtualBoxManager.remote,
     3502           'type':virtualBoxManager.type,
     3503           'run': lambda cmd, args: runCommandCb(ctx, cmd, args),
     3504           'guestlambda': lambda uuid, guestLambda, args: runGuestCommandCb(ctx, uuid, guestLambda, args),
     3505           'machById': lambda uuid: machById(ctx, uuid),
     3506           'argsToMach': lambda args: argsToMach(ctx, args),
     3507           'progressBar': lambda p: progressBar(ctx, p),
    34963508           'typeInGuest': typeInGuest,
    34973509           '_machlist': None,
    3498            'prompt': g_prompt,
     3510           'prompt': g_sPrompt,
    34993511           'scriptLine': 0,
    35003512           'interrupt': False
    35013513           }
    35023514    interpret(ctx)
    3503     g_virtualBoxManager.deinit()
    3504     del g_virtualBoxManager
     3515    virtualBoxManager.deinit()
     3516    del virtualBoxManager
    35053517
    35063518if __name__ == '__main__':
Note: See TracChangeset for help on using the changeset viewer.

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