Python pywintypes.com_error() Examples

The following are 30 code examples of pywintypes.com_error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pywintypes , or try the search function .
Example #1
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def _cached_associated_classes(self):
        if self._associated_classes is None:
            if isinstance(self, _wmi_class):
                params = {'bSchemaOnly': True}
            else:
                params = {'bClassesOnly': True}
            try:
                associated_classes = dict(
                    (assoc.Path_.Class, _wmi_class(self._namespace, assoc)) for
                    assoc in self.ole_object.Associators_(**params)
                )
                _set(self, "_associated_classes", associated_classes)
            except pywintypes.com_error:
                handle_com_error()
        
        return self._associated_classes 
Example #2
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def associators(self, wmi_association_class="", wmi_result_class=""):
        """Return a list of objects related to this one, optionally limited
        either by association class (ie the name of the class which relates
        them) or by result class (ie the name of the class which would be
        retrieved)::

          c = wmi.WMI ()
          pp = c.Win32_ParallelPort ()[0]

          for i in pp.associators (wmi_association_class="Win32_PortResource"):
            print i

          for i in pp.associators (wmi_result_class="Win32_PnPEntity"):
            print i
        """
        try:
            return [
                _wmi_object(i) for i in \
                self.ole_object.Associators_(
                    strAssocClass=wmi_association_class,
                    strResultClass=wmi_result_class
                )
            ]
        except pywintypes.com_error:
            handle_com_error() 
Example #3
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def __call__(self, timeout_ms=-1):
        """When called, return the instance which caused the event. Supports
         timeout in milliseconds (defaulting to infinite). If the watcher
         times out, :exc:`x_wmi_timed_out` is raised. This makes it easy to support
         watching for multiple objects.
        """
        try:
            event = self.wmi_event.NextEvent(timeout_ms)
            if self.is_extrinsic:
                return _wmi_event(event, None, self.fields)
            else:
                return _wmi_event(
                    event.Properties_("TargetInstance").Value,
                    _wmi_object(event, property_map=self._event_property_map),
                    self.fields
                )
        except pywintypes.com_error:
            handle_com_error() 
Example #4
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def Registry(
        computer=None,
        impersonation_level="Impersonate",
        authentication_level="Default",
        authority=None,
        privileges=None,
        moniker=None
):
    warnings.warn("This function can be implemented using wmi.WMI (namespace='DEFAULT').StdRegProv", DeprecationWarning)
    if not moniker:
        moniker = construct_moniker(
            computer=computer,
            impersonation_level=impersonation_level,
            authentication_level=authentication_level,
            authority=authority,
            privileges=privileges,
            namespace="default",
            suffix="StdRegProv"
        )
    
    try:
        return _wmi_object(GetObject(moniker))
    
    except pywintypes.com_error:
        handle_com_error() 
Example #5
Source File: msg_parser.py    From Python-Digital-Forensics-Cookbook with MIT License 6 votes vote down vote up
def extract_attachments(msg, out_dir):
    attachment_attribs = [
        'DisplayName', 'FileName', 'PathName', 'Position', 'Size'
    ]
    i = 1  # Attachments start at 1
    while True:
        try:
            attachment = msg.Attachments(i)
        except pywintypes.com_error:
            break

        print("\nAttachment {}".format(i))
        print("=" * 15)
        for entry in attachment_attribs:
            print('{}: {}'.format(entry, getattr(attachment, entry,
                                                 "N/A")))
        outfile = os.path.join(os.path.abspath(out_dir),
                               os.path.split(args.MSG_FILE)[-1])
        if not os.path.exists(outfile):
            os.makedirs(outfile)
        outfile = os.path.join(outfile, attachment.FileName)
        attachment.SaveAsFile(outfile)
        print("Exported: {}".format(outfile))
        i += 1 
Example #6
Source File: mcplatform.py    From GDMC with ISC License 6 votes vote down vote up
def askOpenFolderWin32(title, initialDir):
    try:
        desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
                                                              win32gui.GetDesktopWindow(),
                                                              desktop_pidl,
                                                              "Choose a folder",
                                                              0,
                                                              None,
                                                              None
                                                              )
        return shell.SHGetPathFromIDList(pidl)
    except pywintypes.com_error as e:
        if e.args[0] == -2147467259:
            print "Invalid folder selected"
        pass 
Example #7
Source File: gencache.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
	"""Given a COM prog_id, return an object that is using makepy support, building if necessary"""
	disp = win32com.client.Dispatch(prog_id)
	if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
		try:
			ti = disp._oleobj_.GetTypeInfo()
			disp_clsid = ti.GetTypeAttr()[0]
			tlb, index = ti.GetContainingTypeLib()
			tla = tlb.GetLibAttr()
			mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
			GetModuleForCLSID(disp_clsid)
			# Get the class from the module.
			import CLSIDToClass
			disp_class = CLSIDToClass.GetClass(str(disp_clsid))
			disp = disp_class(disp._oleobj_)
		except pythoncom.com_error:
			raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
	return disp 
Example #8
Source File: gencache.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
	"""Generate support for a type library.
	
	Given a PyITypeLib interface generate and import the necessary support files.  This is useful
	for getting makepy support for a typelibrary that is not registered - the caller can locate
	and load the type library itself, rather than relying on COM to find it.
	
	Returns the Python module.

	Params
	typelib_ob -- The type library itself
	progressInstance -- Instance to use as progress indicator, or None to
	                    use the GUI progress bar.
	"""
	import makepy
	try:
		makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand = bForDemandDefault, bBuildHidden = bBuildHidden)
	except pywintypes.com_error:
		return None
	tla = typelib_ob.GetLibAttr()
	guid = tla[0]
	lcid = tla[1]
	major = tla[3]
	minor = tla[4]
	return GetModuleForTypelib(guid, lcid, major, minor) 
Example #9
Source File: gencache.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
	"""Generate support for a type library.
	
	Given the IID, LCID and version information for a type library, generate
	and import the necessary support files.
	
	Returns the Python module.  No exceptions are caught.

	Params
	typelibCLSID -- IID of the type library.
	major -- Integer major version.
	minor -- Integer minor version.
	lcid -- Integer LCID for the library.
	progressInstance -- Instance to use as progress indicator, or None to
	                    use the GUI progress bar.
	"""
	if bGUIProgress is not None:
		print "The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete."

	import makepy
	try:
		makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
	except pywintypes.com_error:
		return None
	return GetModuleForTypelib(typelibCLSID, lcid, major, minor) 
Example #10
Source File: softimagescene.py    From cross3d with MIT License 6 votes vote down vote up
def _setNativeSelection(self, selection):
		"""
			\remarks	implements the AbstractScene._setNativeSelection to select the inputed native objects in the scene
			\param		nativeObjects	<list> [ <PySoftimage.xsi.Object> nativeObject, .. ]
			\return		<bool> success
		"""
		if isinstance(selection, basestring):
			try:
				xsi.SelectObj(selection)
			except com_error:
				pass
			finally:
				return True
		else:
			xsiCollSelection = xsiFactory.CreateObject('XSI.Collection')
			xsiCollSelection.AddItems(selection)
			xsi.SelectObj(xsiCollSelection)
		return True 
Example #11
Source File: application.py    From pycatia with MIT License 6 votes vote down vote up
def active_document(self):
        """
        .. admonition:: Note

            CAA V5 Visual Basic Help (2020-06-11 12:40:47.360445)

            | o Property ActiveDocument() As Document (Read Only)
            |
            |     Returns the active document. The active document is the document the end
            |     user is being editing.
            |
            |     Example:
            |         This example retrieves in ActiveDoc the active document of the CATIA
            |         application.
            |
            |          Dim ActiveDoc As Document
            |          Set ActiveDoc = CATIA.ActiveDocument

        :return: Document()
        """
        try:
            return Document(self.application.ActiveDocument)
        except com_error:
            raise CATIAApplicationException('Is there an active document?') 
Example #12
Source File: NatTraversal.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, traverser):
        NATBase.__init__(self)

        self.upnpnat = None
        self.port_collection = None
        self.traverser = traverser
        
        win32com.client.pythoncom.CoInitialize()
        
        try:
            self.upnpnat = win32com.client.Dispatch("HNetCfg.NATUPnP")
        except pywintypes.com_error, e:
            if (e[2][5] == -2147221005):
                raise WindowsUPnPException("invalid class string")
            else:
                raise 
Example #13
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def set(self, **kwargs):
        """Set several properties of the underlying object
        at one go. This is particularly useful in combination
        with the new () method below. However, an instance
        which has been spawned in this way won't have enough
        information to write pack, so only try if the
        instance has a path.
        """
        if kwargs:
            try:
                for attribute, value in kwargs.items():
                    if attribute in self.properties:
                        self._cached_properties(attribute).set(value)
                    else:
                        raise AttributeError(attribute)
                #
                # Only try to write the attributes
                #  back if the object exists.
                #
                if self.ole_object.Path_.Path:
                    self.ole_object.Put_()
            except pywintypes.com_error:
                handle_com_error() 
Example #14
Source File: softimagescene.py    From cross3d with MIT License 6 votes vote down vote up
def _addToNativeSelection(self, selection):
		"""
			\remarks	implements the AbstractScene._addToNativeSelection to select the inputed native objects in the scene
			\param		nativeObjects	<list> [ <PySoftimage.xsi.Object> nativeObject, .. ]
			\return		<bool> success
		"""
		if isinstance(selection, basestring):
			try:
				xsi.AddToSelection(selection)
			except com_error:
				pass
			finally:
				return True
		else:
			xsiCollSelection = xsiFactory.CreateObject('XSI.Collection')
			xsiCollSelection.AddItems(selection)
			xsi.AddToSelection(xsiCollSelection) 
Example #15
Source File: wmi.py    From opsbro with MIT License 6 votes vote down vote up
def handle_com_error(err=None):
    """Convenience wrapper for displaying all manner of COM errors.
    Raises a :exc:`x_wmi` exception with more useful information attached

    :param err: The structure attached to a `pywintypes.com_error`
    """
    if err is None:
        _, err, _ = sys.exc_info()
    hresult_code, hresult_name, additional_info, parameter_in_error = err.args
    hresult_code = signed_to_unsigned(hresult_code)
    exception_string = ["%s - %s" % (hex(hresult_code), hresult_name)]
    scode = None
    if additional_info:
        wcode, source_of_error, error_description, whlp_file, whlp_context, scode = additional_info
        scode = signed_to_unsigned(scode)
        exception_string.append("  Error in: %s" % source_of_error)
        exception_string.append("  %s - %s" % (hex(scode), (error_description or "").strip()))
    for error_code, klass in WMI_EXCEPTIONS.items():
        if error_code in (hresult_code, scode):
            break
    else:
        klass = x_wmi
    raise klass(com_error=err) 
Example #16
Source File: parameters.py    From pycatia with MIT License 5 votes vote down vote up
def is_parameter(self, index):
        """
        :param str or int index: parameter name or parameter number
        :return: bool
        """
        try:
            if self.parameters.Item(index):
                return True
        except com_error:
            return False 
Example #17
Source File: pywin32_testutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def check_is_admin():
    global _is_admin
    if _is_admin is None:
        from win32com.shell.shell import IsUserAnAdmin
        import pythoncom
        try:
            _is_admin = IsUserAnAdmin()
        except pythoncom.com_error, exc:
            if exc.hresult != winerror.E_NOTIMPL:
                raise
            # not impl on this platform - must be old - assume is admin
            _is_admin = True 
Example #18
Source File: sampler.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _query(self):  # pylint: disable=E0202
        """
        Query WMI using WMI Query Language (WQL) & parse the results.

        Returns: List of WMI objects or `TimeoutException`.
        """
        try:
            formated_property_names = ",".join(self.property_names)
            wql = "Select {property_names} from {class_name}{filters}".format(
                property_names=formated_property_names, class_name=self.class_name, filters=self.formatted_filters
            )
            self.logger.debug(u"Querying WMI: %s", wql)
        except Exception as e:
            self.logger.error(str(e))
            return []

        try:
            # From: https://msdn.microsoft.com/en-us/library/aa393866(v=vs.85).aspx
            flag_return_immediately = 0x10  # Default flag.
            flag_forward_only = 0x20
            flag_use_amended_qualifiers = 0x20000

            query_flags = flag_return_immediately | flag_forward_only

            # For the first query, cache the qualifiers to determine each
            # propertie's "CounterType"
            includes_qualifiers = self.is_raw_perf_class and self._property_counter_types is None
            if includes_qualifiers:
                self._property_counter_types = CaseInsensitiveDict()
                query_flags |= flag_use_amended_qualifiers

            raw_results = self.get_connection().ExecQuery(wql, "WQL", query_flags)

            results = self._parse_results(raw_results, includes_qualifiers=includes_qualifiers)

        except pywintypes.com_error:
            self.logger.warning(u"Failed to execute WMI query (%s)", wql, exc_info=True)
            results = []

        return results 
Example #19
Source File: mcplatform.py    From MCEdit-Unified with ISC License 5 votes vote down vote up
def askOpenFolderWin32(title, initialDir):
    try:
        desktop_pidl = shell.SHGetFolderLocation(0, shellcon.CSIDL_DESKTOP, 0, 0)
        pidl, display_name, image_list = shell.SHBrowseForFolder (
                                                              win32gui.GetDesktopWindow(),
                                                              desktop_pidl,
                                                              "Choose a folder",
                                                              0,
                                                              None,
                                                              None
                                                              )
        return shell.SHGetPathFromIDList(pidl)
    except pywintypes.com_error as e:
        if e.args[0] == -2147467259:
            print "Invalid folder selected" 
Example #20
Source File: NatTraversal.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _list_ports(self):
        mappings = []

        try:
            for mp in self.port_collection:
                mapping = UPnPPortMapping(mp.ExternalPort, mp.InternalPort, mp.Protocol,
                                          mp.InternalClient, mp.Description)
                mappings.append(mapping)
        except pywintypes.com_error, e:
            # it's the "for mp in self.port_collection" iter that can throw
            # an exception.
            # com_error: (-2147220976, 'The owner of the PerUser subscription is
            #                           not logged on to the system specified',
            #             None, None)
            pass 
Example #21
Source File: NatTraversal.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def unregister_port(self, external_port, protocol):
        try:
            self.port_collection.Remove(external_port, protocol)
            nat_logger.info("unregisterd: %s, %s" % (external_port, protocol))
        except pywintypes.com_error, e:
            if (e[2][5] == -2147352567):
                UPNPError("Port %d:%s not bound" % (external_port, protocol))
            elif (e[2][5] == -2147221008):
                UPNPError("Port %d:%s is bound and is not ours to remove" % (external_port, protocol))
            elif (e[2][5] == -2147024894):
                UPNPError("Port %d:%s not bound (2)" % (external_port, protocol))
            else:
                raise 
Example #22
Source File: NatTraversal.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def register_port(self, mapping):
        try:
            self.port_collection.Add(mapping.external_port, mapping.protocol,
                                     mapping.internal_port, mapping.host,
                                     True, mapping.service_name)
            nat_logger.info("registered: " + str(mapping))
            mapping.d.callback(mapping.external_port)
        except pywintypes.com_error, e:
            # host == 'fake' or address already bound
            #if (e[2][5] == -2147024726):
            # host == '', or I haven't a clue
            #e.args[0] == -2147024894

            #mapping.d.errback(e)

            # detach self so the queue isn't flushed
            self.traverser.detach_service(self)

            if hasattr(mapping, 'original_external_port'):
                mapping.external_port = mapping.original_external_port
                del mapping.original_external_port

            # push this mapping back on the queue            
            self.traverser.register_requests.append(mapping)    

            # resume init services, because we know we've failed
            self.traverser.resume_init_services() 
Example #23
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def _raw_query(self, wql):
        """Execute a WQL query and return its raw results.  Use the flags
        recommended by Microsoft to achieve a read-only, semi-synchronous
        query where the time is taken while looping through.
        NB Backslashes need to be doubled up.
        """
        flags = wbemFlagReturnImmediately | wbemFlagForwardOnly
        wql = wql.replace("\\", "\\\\")
        try:
            return self._namespace.ExecQuery(strQuery=wql, iFlags=flags)
        except pywintypes.com_error:
            handle_com_error() 
Example #24
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def instances(self):
        """Return a list of instances of the WMI class
        """
        try:
            return [_wmi_object(instance, self) for instance in self.Instances_()]
        except pywintypes.com_error:
            handle_com_error() 
Example #25
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __getattr__(self, attribute):
        try:
            if attribute in self.properties:
                return _wmi_property(self.Properties_(attribute))
            else:
                return _wmi_object.__getattr__(self, attribute)
        except pywintypes.com_error:
            handle_com_error() 
Example #26
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def references(self, wmi_class=""):
        """Return a list of associations involving this object, optionally
        limited by the result class (the name of the association class).

        NB Associations are treated specially; although WMI only returns
        the string corresponding to the instance of each associated object,
        this module will automatically convert that to the object itself::

          c =  wmi.WMI ()
          sp = c.Win32_SerialPort ()[0]

          for i in sp.references ():
            print i

          for i in sp.references (wmi_class="Win32_SerialPortSetting"):
            print i
        """
        #
        # FIXME: Allow an actual class to be passed in, using
        # its .Path_.RelPath property to determine the string
        #
        try:
            return [_wmi_object(i) for i in self.ole_object.References_(strResultClass=wmi_class)]
        except pywintypes.com_error:
            handle_com_error()


#
# class _wmi_event
# 
Example #27
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def derivation(self):
        """Return a tuple representing the object derivation for
        this object, with the most specific object first::

          pp0 = wmi.WMI ().Win32_ParallelPort ()[0]
          print ' <- '.join (pp0.derivation ())
        """
        try:
            return self.ole_object.Derivation_
        except pywintypes.com_error:
            handle_com_error() 
Example #28
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __setattr__(self, attribute, value):
        """If the attribute to be set is valid for the proxied
        COM object, set that objects's parameter value; if not,
        raise an exception.
        """
        try:
            if attribute in self.properties:
                self._cached_properties(attribute).set(value)
                if self.ole_object.Path_.Path:
                    self.ole_object.Put_()
            else:
                raise AttributeError(attribute)
        except pywintypes.com_error:
            handle_com_error() 
Example #29
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __getattr__(self, attribute):
        """
        Attempt to pass attribute calls to the proxied COM object.
        If the attribute is recognised as a property, return its value;
        if it is recognised as a method, return a method wrapper which
        can then be called with parameters; otherwise pass the lookup
        on to the underlying object.
        """
        try:
            if attribute in self.properties:
                property = self._cached_properties(attribute)
                factory = self.property_map.get(attribute, self.property_map.get(property.type, lambda x: x))
                value = factory(property.value)
                #
                # If this is an association, certain of its properties
                # are actually the paths to the aspects of the association,
                # so translate them automatically into WMI objects.
                #
                if property.type.startswith("ref:"):
                    return WMI(moniker=value)
                else:
                    return value
            elif attribute in self.methods:
                return self._cached_methods(attribute)
            else:
                return getattr(self.ole_object, attribute)
        except pywintypes.com_error:
            handle_com_error() 
Example #30
Source File: wmi.py    From opsbro with MIT License 5 votes vote down vote up
def __repr__(self):
        """
        Indicate both the fact that this is a wrapped WMI object
        and the WMI object's own identifying class.
        """
        try:
            return "<%s: %s>" % (self.__class__.__name__, self.Path_.Path.encode("ascii", "backslashreplace"))
        except pywintypes.com_error:
            handle_com_error()