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 ()
python类com_error()的实例源码
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 ()
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 ()
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
#
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 ()
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 ()
def new (self, **kwargs):
"""This is the equivalent to the raw-WMI SpawnInstance\_
method. Note that there are relatively few uses for
this, certainly fewer than you might imagine. Most
classes which need to create a new *real* instance
of themselves, eg Win32_Process, offer a .Create
method. SpawnInstance\_ is generally reserved for
instances which are passed as parameters to such
`.Create` methods, a common example being the
`Win32_SecurityDescriptor`, passed to `Win32_Share.Create`
and other instances which need security.
The example here is `Win32_ProcessStartup`, which
controls the shown/hidden state etc. of a new
`Win32_Process` instance::
import win32con
import wmi
c = wmi.WMI ()
startup = c.Win32_ProcessStartup.new (ShowWindow=win32con.SW_SHOWMINIMIZED)
pid, retval = c.Win32_Process.Create (
CommandLine="notepad.exe",
ProcessStartupInformation=startup
)
.. warning::
previous versions of this docstring illustrated using this function
to create a new process. This is *not* a good example of its use;
it is better handled with something like the example above.
"""
try:
obj = _wmi_object (self.SpawnInstance_ (), self)
obj.set (**kwargs)
return obj
except pywintypes.com_error:
handle_com_error ()
#
# class _wmi_result
#
def get (self, moniker):
try:
return _wmi_object (self.wmi.Get (moniker))
except pywintypes.com_error:
handle_com_error ()
def instances (self, class_name):
"""Return a list of instances of the WMI class. This is
(probably) equivalent to querying with no qualifiers::
wmi.WMI ().instances ("Win32_LogicalDisk")
# should be the same as
wmi.WMI ().Win32_LogicalDisk ()
"""
try:
return [_wmi_object (obj) for obj in self._namespace.InstancesOf (class_name)]
except pywintypes.com_error:
handle_com_error ()
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 ()
def EnsureMSM():
try:
win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 1, 0)
except pywintypes.com_error:
win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 2, 0)
def EnsureMSM():
try:
win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 1, 0)
except pywintypes.com_error:
win32com.client.gencache.EnsureModule('{0ADDA82F-2C26-11D2-AD65-00A0C9AF11A6}', 0, 2, 0)
def _getException(self):
try:
pythoncom.StgOpenStorage("foo", None, 0)
except pythoncom.com_error, exc:
return exc
self.fail("Didn't get storage exception.")
def testIs(self):
self.failUnless(pythoncom.com_error is pywintypes.com_error)
def testSimple(self):
self.assertRaises(pythoncom.com_error, pythoncom.StgOpenStorage, "foo", None, 0)
def testIdentity(self):
exc = self._getException()
self.failUnless(exc.__class__ is pywintypes.com_error)
def testBaseClass(self):
exc = self._getException()
self.failUnlessEqual(pywintypes.com_error.__bases__, (Exception,))
def testStrangeArgsNone(self):
try:
raise pywintypes.com_error()
self.fail("Expected exception")
except pywintypes.com_error, exc:
self.failUnlessEqual(exc.args, ())
self.failUnlessEqual(exc.hresult, None)
self.failUnlessEqual(exc.strerror, None)
self.failUnlessEqual(exc.argerror, None)
self.failUnlessEqual(exc.excepinfo, None)
def testStrangeArgsNotEnough(self):
try:
raise pywintypes.com_error("foo")
self.fail("Expected exception")
except pywintypes.com_error, exc:
self.failUnlessEqual(exc.args[0], "foo")
self.failUnlessEqual(exc.hresult, "foo")
self.failUnlessEqual(exc.strerror, None)
self.failUnlessEqual(exc.excepinfo, None)
self.failUnlessEqual(exc.argerror, None)
def testStrangeArgsTooMany(self):
try:
raise pywintypes.com_error("foo", "bar", "you", "never", "kn", 0)
self.fail("Expected exception")
except pywintypes.com_error, exc:
self.failUnlessEqual(exc.args[0], "foo")
self.failUnlessEqual(exc.args[-1], 0)
self.failUnlessEqual(exc.hresult, "foo")
self.failUnlessEqual(exc.strerror, "bar")
self.failUnlessEqual(exc.excepinfo, "you")
self.failUnlessEqual(exc.argerror, "never")