Previous page

Next page

Locate page in Contents

Searching for a Virtual Machine

The example provided in this section does not really show anything new but it can be useful when testing the sample code provided in later sections. The sample function below accepts a virtual machine name as a parameter (the name can be partial) and searches for it in the virtual machine list retrieved from the host. If it finds it, it returns the prlsdkapi.Vm object identifying the virtual machine to the caller. The function uses the same approach that was used in the Obtaining the Virtual Machine List section. It obtains the list of virtual machine from the Parallels Service, then iterates through it comparing a virtual machine name to the specified name.

Example

# Obtain a Vm object for the virtual machine specified by its name.

# @param vm_to_find: Name of the virtual machine to find.

#                    Can be a partial name (starts with the specified string).

def search_vm(server, vm_to_find):

  

    try:

        result = server.get_vm_list().wait()

    except prlsdkapi.PrlSDKError, e:

        print "Error: %s" % e

        return            

    

    for i in range(result.get_params_count()):

        vm = result.get_param_by_index(i)

        vm_name = vm.get_name()

        if vm_name.startswith(vm_to_find):

          return vm

  

    print 'Virtual machine "' + vm_to_find + '" not found.'

The following code demonstrates how the function can be called from the main() function.

# Search for a virtual machine specified by name.

search_name = "Windows"

print ""

print "Searching for '" + search_name + "%'"

  

vm = search_vm(server, search_name)

  

if isinstance(vm, prlsdkapi.Vm):

    print "Found virtual machine " + vm.get_name()